DEV Community

TheCodeAlchemist
TheCodeAlchemist

Posted on • Updated on

Java ArrayList for Beginners

ArrayList belongs to the List hierarchy in Java Collection framework.

If you like this article, please give me a thumbs up. Here’s the complete video https://youtu.be/b3WKatSm6lA
ArrayList is an ordered collection which is internally implemented by Array.

Although backed by array which is a fixed-size data structure, ArrayList is dynamically sized meaning it can be resized.

Creating a new ArrayList

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

//adding elements to the list
myList.add("Item1"); //index 0
myList.add("Item2"); //index 1
myList.add("Item3"); //index 2
myList.add("Item4"); //index 3

//getting elements from the list by passing the index to get method
System.out.println(myList.get(0));
System.out.println(myList.get(1));
System.out.println(myList.get(2));
System.out.println(myList.get(3));
Enter fullscreen mode Exit fullscreen mode

We can also set elements by index.

//this will set/update element at index 1 in nums to 21
nums.set(1, 21);
Enter fullscreen mode Exit fullscreen mode

Adding elements to ArrayList in Bulk/Batch

private static void addingElementsFromAnotherCollection(ArrayList<String> myList) {
      //creating a new collection
      ArrayList<String> fromList = new ArrayList<>();
      fromList.add("Item5");
      fromList.add("Item6");

      //Use addAll method to add values from collection fromList to myList in bulk
      myList.addAll(l2);

      System.out.println(myList);
 }
Enter fullscreen mode Exit fullscreen mode

Accessing elements using Iterator and for-each

private static void usingForEach(ArrayList<String> myList) {
    System.out.println("for-each==============");
    for (String element : myList) {
        System.out.println(element);
    }
}

private static void usingIterator(ArrayList<String> myList) {
    System.out.println("Iterator===========");
    Iterator<String> it = myList.iterator();
    while(it.hasNext()) {
        System.out.println(it.next());
    }
}
Enter fullscreen mode Exit fullscreen mode

Finding elements

String toCheck = "Item4";
//returns true if list contains Item4 otherwise returns false
System.out.println(myList.contains(toCheck)); 

//indexOf returns index of first occurrence
//lastIndexOf returns index of first occurrence from the end
System.out.println(myList.indexOf("Item6") + ", " + myList.lastIndexOf("Item6"));
Enter fullscreen mode Exit fullscreen mode

Size related methods

myList.size(); //returns size of the arrayList

//returns true if List is empty
myList.isEmpty();

myList.clear(); //clears the list, removes all elements from the list
Enter fullscreen mode Exit fullscreen mode

Removing elements from the List

private static void removeAndRetain(ArrayList<String> myList) {
    myList.add("Item1");
    myList.add("Item2");
    myList.add("Item3");
    myList.add("Item4");
    myList.add("Item5");
    System.out.println(myList);

    //remove Item3 from the list
    myList.remove("Item3");
    System.out.println(myList);

    //remove element at index 1
    myList.remove(1);
    System.out.println(myList);


    ArrayList<String> tobeDeleted = new ArrayList<>();
    tobeDeleted.add("Item4");
    tobeDeleted.add("Item5");

    //remove Item4 and Intem5 from myList in a single pass
    myList.removeAll(tobeDeleted);
    System.out.println(myList);

    ArrayList<Integer> nums = new ArrayList<>();
    nums.add(1);
    nums.add(2);
    nums.add(3);
    nums.add(4);

    //internally iterates the list elements and applies passed predicate to 
    //each element.
    //All matching elements will be removed from the list
    nums.removeIf(integer -> integer % 2 == 0);

    System.out.println(nums);

    ArrayList<Integer> nums1 = new ArrayList<>();
    nums1.add(5);
    nums1.add(6);
    nums1.add(7);
    nums1.add(8);

    ArrayList<Integer> keepThese = new ArrayList<>();
    keepThese.add(6);
    keepThese.add(7);

    //Opposite of removeAll
    //All elements in nums1 which are not part of passed collection
    //will be removed.
    nums1.retainAll(keepThese);
    System.out.println(nums1);

}
Enter fullscreen mode Exit fullscreen mode

Converting an ArrayList to Array

ArrayList<Integer> nums = new ArrayList<>();
nums.add(1); //0
nums.add(2); //1
nums.add(3); //2
nums.add(4); //3

Object[] arr = nums.toArray(); //returns an object array

//An explicit cast is required to convert object[]
Integer[] arr = (Integer[]) nums.toArray();

//This doesn't need an explicit cast
//this version can infer the type from array type passed to toArray(..)
Integer[] arr = nums.toArray(new Integer[0]);
Enter fullscreen mode Exit fullscreen mode

Performing an action on each element

//passed consumer will be applied to all elements
myList.forEach(s -> System.out.println(s.toUpperCase()));
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
cicirello profile image
Vincent A. Cicirello

Your variable names in examples are bad choices. It is hard to read l1 appropriately because it looks nearly identical to 11 which isn't valid. Same with l2 which then looks like 12.

Collapse
 
therealdumbprogrammer profile image
TheCodeAlchemist

I agree. Thanks for pointing it out.