Easy way to IT Job

Java ArrayList Example
Share on your Social Media

Java ArrayList Example

Published On: April 6, 2024

Storage and data manipulation are essential components of software development in the field of Java programming. Java has a variety of data structures, but ArrayList is one of the most flexible and dynamic of all. This article will go into great detail about Java’s ArrayList, including its capabilities, advantages, recommended practices, and usage examples. Learn more about Java ArrayList through our Java course syllabus with 100% hands-on exposure at Softlogic.

Understanding ArrayList

An ArrayList object includes object references and is changeable, meaning it can change by having items added or removed. The ArrayList() constructor generates an empty list with size zero. 

What is an ArrayList?

A resizable array, known as an ArrayList class, is a component of the Java util package. As opposed to built-in arrays, which have a fixed size, ArrayLists allow for dynamic size changes. An ArrayList allows elements to be added and removed as needed, helping in memory management for the user. 

Java’s ArrayList allows for duplicate elements as well. We can utilize all of the List interface’s methods because it implements the List interface. The ArrayList internally keeps track of the insertion order.

It implements the List interface and derives from the AbstractList class. The following are important details of the Java ArrayList class: 

  • Elements in the Java ArrayList class may be duplicates.
  • The ArrayList class in Java preserves insertion order.
  • The ArrayList class in Java lacks synchronization.
  • Because the array is index-based, random access is possible with Java ArrayLists.
  • Because a lot of shifting must happen whenever an element is removed from the array list, the manipulation of an ArrayList in Java is a little bit slower than that of a LinkedList.

An array list of primitive kinds, such as int, float, char, etc., cannot be created. In these situations, using the necessary wrapper class is necessary. 

Example

ArrayList<int> al = ArrayList<int>(); // It will not work

ArrayList<Integer> al = new ArrayList<Integer>(); // It will work as intended

The size initializes a Java ArrayList. The array list’s size is dynamic and changes based on which entries are added to or removed from the list. Explore the strings in Java here.

How does it differ from arrays?

An array’s size must be declared in Java before it may be used. It is difficult to alter an array’s size once it has been declared. We can utilize the ArrayList class to deal with this problem. We can make resizable arrays with it. 

When we add or delete entries from arraylists, they can automatically change in capacity, unlike arrays. Thus, dynamic arrays are another name for arraylists.

Creating an ArrayList: Java ArrayList Example

We must import the java.util.ArrayList package before we can use ArrayList. The following is how to make arraylists in Java:

arrayList= new ArrayList<>(); ArrayList arrayList

In this case, type denotes the arraylist’s type.

Example

ArrayList<>() creates a new ArrayList arrayList;  //builds an arraylist of integer types.

ArrayList<>() creates a new ArrayList arrayList; // construct an arraylist of String type

We used integers rather than int in the program mentioned above. This is because, while building an ArrayList, primitive types cannot be used. We must instead make use of the appropriate wrapper classes. In this case, the matching wrapper class for int is called Integer. Go to the Java wrapper class to find out more.

Creating a Java ArrayList Example:

import java.util.ArrayList;

class Main {

  public static void main(String[] args){

    ArrayList<String> languages = new ArrayList<>();

    languages.add(“Java”);

    languages.add(“Python”);

    languages.add(“Swift”);

    System.out.println(“ArrayList: ” + languages);

  }

}

Output

ArrayList: [Java, Python, Swift]

We have constructed an ArrayList named languages in the example above. Here, we have added elements to the arraylist using the add() method.

Java-related Articles on Softlogic: Object Methods in Java | Types of Java Applications.

Dynamic Resizing: ArrayList’s Resizable Capacity

The ArrayList class creates a new array of greater size and copies all of the entries from the old array to the new array whenever it needs to resize, which is how the ArrayList size grows dynamically. It is currently using the internal reference of the new array. The previous garbage collection will include the old array since it is no longer in use. 

Arrays are known to be fixed-length data structures; once they are generated, they cannot be resized. In contrast, ArrayLists can automatically resize themselves in response to load factors and capacity issues. To learn about the default size of 10, let’s make an example of an ArrayList using the default constructor.  

Example

public class CreateArrayListExample {

    public static void main(String[] args) {

     List<String> animals = new ArrayList<>();

        animals.add(“Lion”);

        animals.add(“Tiger”);

        animals.add(“Cat”);

        animals.add(“Dog”);

        System.out.println(animals);

        animals.add(2, “Elephant”);

        System.out.println(animals);

    }

}

Output

[Lion, Tiger, Cat, Dog]

[Lion, Tiger, Elephant, Cat, Dog]

An ArrayList instance is created using the default constructor, as demonstrated in the example above. 

new ArrayList<>(); – Creates a blank list with 10 entries at the beginning.

Suggested Blog: Top 10 Interesting Facts about Java.

ArrayList Operations

The ArrayList class has many methods for working with arraylists. In this article, we’ll examine a few frequently used arraylist operations: 

Adding elements: add() method.

The ArrayList class’s add() method is used to add a single element to the arraylist. 

Example

import java.util.ArrayList;

class Main {

  public static void main(String[] args){

    ArrayList<String> languages = new ArrayList<>();     // Creating ArrayList

    languages.add(“Java”);     

    languages.add(“C”);

    languages.add(“Python”);

    System.out.println(“ArrayList: ” + languages);

  }

}

Output

ArrayList: [Java, C, Python]

We created an ArrayList of programming languages in the example above. Here, we’ve added items to languages using the add() method.

Accessing elements: get() method

We utilize the ArrayList class’s get() method to retrieve an element from the arraylist.

Example

import java.util.ArrayList;

class Main {

  public static void main(String[] args) {

    ArrayList<String> animals = new ArrayList<>();

    animals.add(“Cat”); // adding elements in the arraylist

    animals.add(“Dog”);

    animals.add(“Cow”);

    System.out.println(“ArrayList: ” + animals);

    String str = animals.get(1);     // access the element from the arraylist

    System.out.print(“Element at index 1: ” + str);

  }

}

Output

ArrayList: [Cat, Dog, Cow]

Element at index 1: Dog

We used the get() method with parameter 1 in the example above. In this example, the operation returns the element at index 1. Join our Java internship training in Chennai to get more hands-on practice on Java concepts.

Updating elements: set() method

The set() function of the ArrayList class is used to modify the arraylist’s elements.

Example

import java.util.ArrayList;

class Main {

  public static void main(String[] args) {

    ArrayList<String> languages = new ArrayList<>();

    languages.add(“Java”);

    languages.add(“Kotlin”);

    languages.add(“C++”);

    System.out.println(“ArrayList: ” + languages);

    languages.set(2, “JavaScript”);   // modify the element of the array list

    System.out.println(“Modified ArrayList: ” + languages);

  }

}

Output

ArrayList: [Java, Kotlin, C++]

Modified ArrayList: [Java, Kotlin, JavaScript]

We have created an ArrayList named programming languages in the example above. 

Take note of the line. 

language.set(2, “JavaScript”);

In this case, the element at index 2 is changed to JavaScript via the set() method. 

Related Blog: Kotlin vs Java: Which is the best fit for mobile app development?

Removing elements: remove() method

The ArrayList class’s remove() method can be used to remove an element from the arraylist.  

Example

import java.util.ArrayList;

class Main {

  public static void main(String[] args) {

    ArrayList<String> animals = new ArrayList<>();

    animals.add(“Dog”);

    animals.add(“Cat”);

    animals.add(“Horse”);

    System.out.println(“ArrayList: ” + animals);

    // remove element from index 2

    String str = animals.remove(2);

    System.out.println(“Updated ArrayList: ” + animals);

    System.out.println(“Removed Element: ” + str);

  }

}

Output

ArrayList: [Dog, Cat, Horse]

Updated ArrayList: [Dog, Cat]

Removed Element: Horse

The index number is the input that the delete() method accepts in this case. Additionally, the element that the index number designates is removed.

Iterating through elements: Using loops or iterators.

To iterate through each element of the arraylist, we can utilize Java’s ‘for-each’ loop.

Example

import java.util.ArrayList;

class Main {

  public static void main(String[] args) {

    // creating an array list

    ArrayList<String> animals = new ArrayList<>();

    animals.add(“Cow”);

    animals.add(“Cat”);

    animals.add(“Dog”);

    System.out.println(“ArrayList: ” + animals);

    // iterate using for-each loop

    System.out.println(“Accessing individual elements:  “);

    for (String language : animals) {

      System.out.print(language);

      System.out.print(“, “);

    }

  }

}

Output

ArrayList: [Cow, Cat, Dog]

Accessing individual elements:  

Cow, Cat, Dog,

Kick-start your career by understanding the Java fundamentals, which are easy for beginners.

Methods of ArrayList Class

The ArrayList class’s add(), get(), set(), and delete() methods were covered in the preceding section. Here are a few additional frequently used ArrayList methods in addition to those fundamental ones.

MethodsDescriptions
size()It returns the arraylist’s length. 
sort()It sorts out the length of the arraylist.
clone()It creates a fresh arraylist with the same capacity, size, and element. 
contains()It finds the specified element in the arraylist and returns a boolean result. 
ensureCapacity()It lets you know how many elements the arraylist can hold in total.
isEmpty()It determines if the arraylist is null. 
indexOf()It returns the element’s index after searching for a given element in an arraylist. 

Generics and Type Safety

Programmers can create customizable, type-safe, and easier-to-read generic algorithms that operate on collections of various kinds by utilizing generics. 

Introduction to Generics in Java

Type safety is the key justification for using generics. Errors can be detected at compilation, which is far safer than doing so during runtime, thanks to generics. In the absence of generics, casts may fail at runtime, resulting in a ClassCastException and potentially difficult-to-debug issues.

Example

List list = new ArrayList();

list.add(“hello”);

String s = (String) list.get(0);

This code is not type-safe, but it compiles without errors. A ClassCastException would be thrown at runtime by the code if we unintentionally introduced an object that wasn’t a String.

Let’s now employ a general List:

List<String> list = new ArrayList<>();

list.add(“hello”);

String s = list.get(0); // No cast required.

Specifying the type of elements in ArrayList.

Java allows the generic type ArrayList, in which the generic type E specifies the kinds of members (such as strings or integers). Without it, the type will be an object.

public E set(int index, E element)

To set an element in an ArrayList object at a certain index, use the ArrayList.set() function. 

Package: java.util

Java Platform: Java SE8

Syntax

set(int index, E element)

Parameters

index: An element’s index is to be set.

element: element to be stored at the particular position.

Example

import java.util.*;

public class test {

   public static void main(String[] args) { 

    ArrayList<String> color_list = new ArrayList<String>(5);

    color_list.add(“White”);

    color_list.add(“Black”);

    color_list.add(“Red”);

    color_list.add(“White”);

color_list.add(“Yellow”);

    color_list.set(2, new String(“Violet”));

    for (int i = 0; i < 5; i++)

      {

         System.out.println(color_list.get(i).toString());

      }

  }

}   

Output

F:\java>javac test.java

F:\java>java test

White

Black

Violet

White

Yellow.

Explore our Java interview questions and answers and review your skills.

Compile-time type safety with generics.

Java programming’s type safety is based primarily on generics. They help developers avoid frequent issues like ClassCastException by enabling them to guarantee compatible data types used within a program at compile time. We’ll explore the value of type safety, how generics improve it, and how it affects Java developers in this part.

Compile-time Checking

Since type safety with generics is mainly enforced at build time, mistakes can be found and fixed before the program is even executed. Large software projects benefit greatly from this early detection since it shortens the time needed for debugging and increases code stability.

Example

List<String> stringList = new ArrayList<>();

stringList.add(“Java”);

Because of generics, attempting to add an integer to a list of string objects results in a compile-time error. Type safety is ensured via generics; the Java compiler enforces this by verifying consistency and inspecting the type.

Avoiding runtime errors through type checking

Give the template type checker more detailed in-template type requirements to help prevent run-time type mistakes. Provide template-guard functions in the directive specification to let you be as specific as possible with the input type requirements for your directives. 

Refrain from utilizing variables that need initialization. On your system, these might be set to 0, but not on the coding platform. Verify that every instance of an array element is not out of bounds. Refrain from overstating your memories. Runtime checking ensures that the types are implemented as well as part of the API, reducing the number of minor gaps that users may rely on. You can find more about them in our core Java course syllabus.

Common ArrayList Use Cases

Runtime checking ensures that the types are implemented as well as part of the API, reducing the number of minor gaps that users may rely on. Here are some common use cases of arraylists in Java.

Storing and managing collections of objects.

import java.util.ArrayList;

public class StoreObjectsInAnArrayList {

public static void main(String[] args) {

ArrayList<Employee> empList = new ArrayList<>();

Employee emp1 = new Employee(1, “BMW”, “USA”);

Employee emp2 = new Employee(2, “Skoda”, “Japan”);

Employee emp3 = new Employee(3, “Ford”, “Germany”);

Employee emp4 = new Employee(4, “Suzuki”, “canada”);

//adding the objects into ArrayList

empList.add(emp1);

empList.add(emp2);

empList.add(emp3);

empList.add(emp4);

//Display the objects of an ArrayList using for-each

System.out.println(“—-Employee objects—“);

for(Employee emp:empList){

emp.display();

System.out.println();

}

}

}

class Employee {

int id;

String name;

String address;

public Employee(int id, String name, String address) {

this.id = id;

this.name = name;

this.address = address;

}

public void display(){

System.out.println(“Id:”+id);

System.out.println(“EmpName:”+name);

System.out.println(“EmpAddres:”+address);

}

}

Article Recommendation: Differences Between General Training and Specific Training.

Implementing dynamic lists in applications

The java.util package has an ArrayList class, which is a dynamic array. Built-in arrays are fixed in size, whereas ArrayList allows you to dynamically alter their size. An ArrayList allows elements to be added and removed as needed, which aids in memory management for the user.

The following are key details regarding the Java Array List class:

  • Elements in the Java Array List class may be duplicates.
  • The Java Array List class saves the order of insertion.
  • Because arrays operate on an index basis, Java Array Lists permit random access. 
Example

ArrayList<Type> arrayList= new ArrayList<>();

import java.util.ArrayList;

class Main {

 public static void main(String[] args){

   // create ArrayList

   ArrayList<String> fruits = new ArrayList<>(); // ArrayList with String type

   // Add elements to ArrayList

   fruits.add(“apple”);

   fruits.add(“mango”);

   fruits.add(“banana”);

   System.out.println(“ArrayList: ” + fruits);

 }

}

Output

ArrayList: [apple, mango, banana] */

Recommended Read: What are the skills of an IT employee?

Facilitating data manipulation and processing

Following our understanding of the idea and prerequisites for ArrayLists, the code to sort an ArrayList using the two previously stated methods is shown below.

To Sort in Ascending Order

import java.util.*;    

public class Main 

{  

public static void main (String[]args)

  {

    ArrayList < String > list = new ArrayList < String > ();

    list.add (“Apple”);

    list.add (“Orange”);

    list.add (“Cherry”);

    list.add (“Apricot”);

    System.out.println (“Before: ” + list);

    Collections.sort (list);

    System.out.println (“After: ” + list);

   } 

}

Output

Before: [Apple, Orange, Cherry, Apricot]

After: [Apple, Apricot, Cherry, Orange]

The code above creates an ArrayList class object and uses the add() function to append several strings to the ArrayList. After performing the sort() process and printing the ArrayList, we can see that the output ArrayList is arranged lexicographically in ascending order.

Explore the top demand jobs in 2024 for IT aspirants and hone your skills with Java.

Integrating with Java Collections Framework

Java’s Collection framework consists of classes and interfaces that can be used to store things. This diagram can assist in determining which containers are appropriate for the various storage capacities.

Reasons to use ArrayList

The use of array lists is superior since they provide greater flexibility than static arrays, which require a fixed place to keep the components upon allocation. This is because array lists are stored dynamically and have no size restriction.

  • Because it inherits the Abstract List Class, it is ensured to have access to all of the features and attributes of a list in addition to its own.
  • To use ArrayList, we must import it from the java.util package to create the collection framework class.

Java is one of the easiest programming languages to learn for beginners. Enroll today at Softlogic Systems.

Best Practices of ArrayList in Java

  • Declare an initial capacity for an ArrayList.
  • Select the right collection types under the specifications.
  • Make use of an improved for-loop to iterate.
  • Make sure concurrent environments maintain thread safety. 

Real-World Applications of ArrayList in Java

If searching is a more frequent activity than add and remove operations, then it is preferable to use an ArrayList since it offers a consistent time for search operations. An ArrayList’s get and set operations have an O(1) time complexity for accessing elements. Following are the real-world applications of ArrayList in Java

  • Database management systems.
  • Graphical user interfaces (GUIs).
  • Web development frameworks.
  • Data processing pipelines.

Pitfalls and Common Mistakes of ArrayList in Java

  • Forgetting to specify the type of element.
  • Inefficient resizing strategies lead to performance degradation.
  • Incorrectly handling concurrent modifications.

Explore the top programming languages for the future and upgrade yourself.

Conclusion

Java’s ArrayList is a basic data structure for effectively managing dynamic collections of things. Developers can harness its ability to create scalable and reliable applications in a variety of fields by learning about its features, functions, and recommended practices. Whether you’re a novice or an experienced Java developer, creating software that works well requires an understanding of ArrayList. Enroll in our Java training in Chennai and get equipped for next-gen careers in the IT sector.

Share on your Social Media

Just a minute!

If you have any questions that you did not find answers for, our counsellors are here to answer them. You can get all your queries answered before deciding to join SLA and move your career forward.

We are excited to get started with you

Give us your information and we will arange for a free call (at your convenience) with one of our counsellors. You can get all your queries answered before deciding to join SLA and move your career forward.