Java ArrayList: Important Methods You Should Know
Java ArrayList: Key Methods to Know
Let's create a Java class named ArrayListMethods
with various methods for creating and manipulating ArrayLists of different data types. The class contains static methods for creating ArrayLists of integers, strings, and generic types. This class also demonstrates how you can add data to an ArrayList. The main method in the class creates and manipulates these ArrayLists to showcase various ArrayList methods and operations.
public class ArrayListMethods {
public static ArrayList<Integer> getIntArrayList(int a, int b, int c, int d, int e) {
ArrayList<Integer> ar = new ArrayList<>(Arrays.asList(a, b, c, d, e));
return ar;
}
public static ArrayList<String> getStringArrayList(String a, String b, String c, String d) {
ArrayList<String> ar = new ArrayList<>();
ar.add(a);
ar.add(b);
ar.add(c);
ar.add(d);
return ar;
}
public static <T> ArrayList<T> getTArrayList(T a, T b, T c, T d, T e) {
ArrayList<T> ar = new ArrayList<>(Arrays.asList(a,b,c,d,e));
return ar;
}
public static <T> ArrayList<T> getTArrayList(T a, T b, T c, T d, T e,T f, T g, T h, T i, T j, T k, T l, T m, T n) {
ArrayList<T> ar = new ArrayList<>(Arrays.asList(a,b,c,d,e,f, g, h, i, j, k, l, m, n));
return ar;
}
Here's a brief explanation of the selected code:
getIntArrayList(int a, int b, int c, int d, int e)
: This method creates an ArrayList of integers with the given elements.getStringArrayList(String a, String b, String c, String d)
: This method creates an ArrayList of strings with the given elements.getTArrayList(T a, T b, T c, T d, T e)
: This method creates an ArrayList of a generic type T with the given elements.getTArrayList(T a, T b, T c, T d, T e, T f, T g, T h, T i, T j, T k, T l, T m, T n)
: This overloaded method creates an ArrayList of a generic type T with the given elements.
Now, lets create some ArrayList by using these methods.
public static void main(String[] args) {
System.out.println(" ****ArrayList Methods****\n");
ArrayList<Integer> intArray1 = getIntArrayList(10, 20, 30, 40, 50);
ArrayList<Integer> intArray2 = getIntArrayList(100, 200, 300, 400, 500);
ArrayList<Integer> intArray3 = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
ArrayList<String> stringArray = getStringArrayList("gb", "AT", "aS", "pd");
ArrayList<String> genericArray = getTArrayList("gb", "AT", "aS", "pd", "sd");
ArrayList<String> genericArray1 = getTArrayList("gb", "AT", "aS", "pd", "sd");
ArrayList<String> genericArray2 = getTArrayList("gb", "AT", "aS", "pd", "sd");
}
Here, in the main method, several ArrayLists are created using these methods and then manipulated with various ArrayList operations. The code below shows how to use different ArrayList methods and collection functions. After creating several ArrayLists of different types (Integer, String, and generic), let's perform various operations on them, such as sorting, adding elements, removing elements, and using sublists. This code aims to demonstrate the functionality of ArrayLists and Collections in Java.
Collections.sort() and set()
//Sorting
Collections.sort(intArray1);
System.out.println(intArray1);
//set
intArray1.set(0,80);
System.out.println(intArray1);
//1:Output [10, 20, 30, 40, 50]
//2:Output [80, 20, 30, 40, 50]
The above snippet is part of the main method in the ArrayListMethods class. It shows how to use the Collections.sort()
method to sort an ArrayList of integers and how to use the set()
method to change the value of an element at a specific index.
The Collections.sort()
method sorts the intArray1
ArrayList in ascending order. After sorting, the sorted ArrayList is printed to the console. The set()
method then changes the value of the first element in the intArray1
ArrayList from its original value (the smallest value after sorting) to 80. The updated ArrayList is printed to the console again.
addAll(), clear(), and isEmpty()
//The purpose of this code snippet is to showcase
//the usage of addAll, clear, and isEmpty methods on ArrayLists.
ArrayList<Integer> partialCopyArrayList = new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5));
partialCopyArrayList.addAll(4, intArray2);
System.out.println(partialCopyArrayList);
intArray1.addAll(intArray2);
System.out.println(intArray1);
System.out.println("genericArray"+genericArray);
System.out.println("genericArray.isEmpty() "+genericArray.isEmpty());
genericArray.clear();
System.out.println(genericArray);
System.out.println("genericArray.isEmpty() "+genericArray.isEmpty() + "\n");
//Output:
//[0, 1, 2, 3, 100, 200, 300, 400, 500, 4, 5]
//[80, 20, 30, 40, 50, 100, 200, 300, 400, 500]
//genericArray[gb, AT, aS, pd, sd]
//genericArray.isEmpty() false
//[]
//genericArray.isEmpty() true
This code snippet is part of the main method in the ArrayListMethods class. It demonstrates several ArrayList methods such as addAll, clear, and isEmpty.
First, it creates a new ArrayList called partialCopyArrayList with initial elements (0, 1, 2, 3, 4, 5). Then, it adds elements from another ArrayList (intArray2) starting from the 4th index (0-based index) using the addAll method. The updated partialCopyArrayList is then printed.
Next, it adds all elements from intArray2 to another ArrayList called intArray1 using the addAll method. The updated intArray1 is then printed.
Then, it prints the genericArray and checks if it's empty using the isEmpty method. After that, it clears the genericArray using the clear method and prints it again along with the isEmpty result.
The clone()
This method is a built-in method in Java that is used to create a copy of an object. In the context of ArrayLists, it creates a new ArrayList with the same elements as the original ArrayList. However, it's important to note that the clone() method does not create a deep copy of the ArrayList, meaning that any changes made to the elements of the cloned ArrayList will also affect the original ArrayList.
System.out.println("//.Clone() Method");
ArrayList<Integer> cloneArray = (ArrayList) (intArray1.clone());
ArrayList<Object> objClone = (ArrayList) intArray2.clone();
ArrayList<String> stringClone = (ArrayList) stringArray.clone();
System.out.println(cloneArray);
System.out.println(objClone);
System.out.println(stringClone + "\n");
//Output:
//[80, 20, 30, 40, 50, 100, 200, 300, 400, 500]
//[100, 200, 300, 400, 500]
//[gb, AT, aS, pd]
In this code, three ArrayLists are cloned: cloneArray
is cloned from intArray1
, objClone
is cloned from intArray2
, and stringClone
is cloned from stringArray
. The cloned ArrayLists are then printed to the console.
The clone() method in Java makes a copy of an object. For ArrayLists, it creates a new ArrayList with the same elements as the original. However, it doesn't make a deep copy, so changes to the elements in the cloned ArrayList will also change the original ArrayList.
The contains() and indexOf()
This method checks if an element is present in the ArrayList. The indexOf() method returns the index of the first occurrence of the specified element in the ArrayList. The lastIndexOf() method returns the index of the last occurrence of the specified element in the ArrayList.
//The code snippet is a part of the main method in the ArrayListMethods class.
//It demonstrates the usage of the contains(), indexOf(), and lastIndexOf() methods on ArrayList objects.
System.out.println("//.contains() & .indexOf() Method");
System.out.println("stringArray.contains(500))= " + stringArray.contains(500));
System.out.println("intArray2.contains(500))= " + (intArray2.contains(500)));
System.out.println("intArray1.indexOf(500) =" + intArray1.indexOf(500));
int i = intArray2.lastIndexOf(100);
System.out.println("intArray2.lastIndexOf(100) =" + i + "\n");
//Output
//stringArray.contains(500))= false
//intArray2.contains(500))= true
//intArray1.indexOf(500) =9
//intArray2.lastIndexOf(100) =0
In the code snippet, the program checks if the ArrayLists stringArray and intArray2 contain the element 500, and it also finds the index of the element 100 in intArray2. The results are then printed to the console.
remove()
The following code snippet shows how to use the remove method to modify the contents of an ArrayList in Java.
//this code snippet is a part of the main method in the ArrayListMethods class.
// It demonstrates how to use the remove method of the
//ArrayList class in Java to remove specific elements from the list.
System.out.println("//remove(100,200,AT)");
intArray2.remove((Integer) 200);
intArray2.remove((Integer) 100);
stringArray.remove("AT");
System.out.println("intArray2 =" + intArray2 + "\n" + "stringArray =" + stringArray + "\n");
//Output
//intArray2 =[300, 400, 500]
//stringArray =[gb, aS, pd]
In this code, the remove method is called on the intArray2
and stringArray
ArrayLists. The remove method takes an argument that specifies the element to be removed from the ArrayList. In this case, the argument is an Integer object for intArray2
and a String object for stringArray
.
After removing the specified elements, the updated ArrayLists are printed to the console. The output will show the remaining elements in the ArrayLists after the removal operation.
Collections.singleton() and subList ()
The below code shows the usage of Collections.singleton()
and subList methods
//The selected code snippet is a part of the main method in the
//ArrayListMethods class. It demonstrates the usage of
//Collections.singleton and subList methods
System.out.println("//Collections.singleton,subList");
genericArray1.retainAll(Collections.singleton("aS"));
System.out.println("Collections.singleton =" + genericArray1);
// Creating a sublist from the ArrayList
ArrayList<String> subList = new ArrayList<>(genericArray2.subList(0, 3));
System.out.println("subList =" + subList + "\n");
//Output
//Collections.singleton =[aS]
//subList =[gb, AT, aS]
Collections.singleton:
This method returns a set containing a single element. In the code, it is used to create a set containing the string "aS". The retainAll
method is then called on genericArray1 to remove all elements that are not in the singleton set.
subList:
This method returns a view of the portion of the list between the specified fromIndex, inclusive, and toIndex, exclusive. In the code, it is used to create a sublist of genericArray2 containing the first three elements.
removeIf()
The selected code is a part of the main method in the ArrayListMethods class. It demonstrates the usage of the removeIf
method on an ArrayList of integers called intArray3
System.out.println("removeIf()");
intArray3.removeIf(number -> number % 2 != 0);
System.out.println(intArray3);
//Output
//[2, 4, 6, 8, 10]
This method removes all elements from the ArrayList that satisfy the given predicate (in this case, the lambda expression number -> number % 2 != 0). This lambda expression checks if a number is odd (i.e., its remainder when divided by 2 is not zero), and if so, it removes that number from the ArrayList. After the removeIf
method is called, the updated ArrayList is printed to the console.
Subscribe to my newsletter
Read articles from Ashish Thakur directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by