ArrayList in Java is used to store dynamically sized collection of elements. Contrary to Arrays that are fixed in size, an ArrayList grows its size automatically when new elements are added to it.
ArrayList is part of Java’s collection framework and implements Java’s List interface.
Following are few key points to note about ArrayList in Java -
An ArrayList is a re-sizable array, also called a dynamic array. It grows its size to accommodate new elements and shrinks the size when the elements are removed.
ArrayList internally uses an array to store the elements. Just like arrays, It allows you to retrieve the elements by their index.
Java ArrayList allows duplicate and null values.
Java ArrayList is an ordered collection. It maintains the insertion order of the elements.
You cannot create an ArrayList of primitive types like int, char etc. You need to use boxed types like Integer, Character, Boolean etc.
Java ArrayList is not synchronized. If multiple threads try to modify an ArrayList at the same time, then the final outcome will be non-deterministic. You must explicitly synchronize access to an ArrayList if multiple threads are gonna modify it.
Creating an ArrayList and adding new elements to it
This example shows:
How to create an ArrayList using the ArrayList() constructor.
Add new elements to an ArrayList using the add() method.
importjava.util.ArrayList;importjava.util.List;publicclassCreateArrayListExample {publicstaticvoidmain(String[] args) {// Creating an ArrayList of StringList<String> animals =newArrayList<>();// Adding new elements to the ArrayListanimals.add("Lion");animals.add("Tiger");animals.add("Cat");animals.add("Dog");System.out.println(animals);// Adding an element at a particular index in an ArrayListanimals.add(2,"Elephant");System.out.println(animals); }}
How to create an ArrayList from another collection using the ArrayList(Collection c)constructor.
How to add all the elements from an existing collection to the new ArrayList using the addAll()method.
importjava.util.ArrayList;importjava.util.List;publicclassCreateArrayListFromCollectionExample {publicstaticvoidmain(String[] args) {List<Integer> firstFivePrimeNumbers =newArrayList<>();firstFivePrimeNumbers.add(2);firstFivePrimeNumbers.add(3);firstFivePrimeNumbers.add(5);firstFivePrimeNumbers.add(7);firstFivePrimeNumbers.add(11);// Creating an ArrayList from another collectionList<Integer> firstTenPrimeNumbers =newArrayList<>(firstFivePrimeNumbers);List<Integer> nextFivePrimeNumbers =newArrayList<>();nextFivePrimeNumbers.add(13);nextFivePrimeNumbers.add(17);nextFivePrimeNumbers.add(19);nextFivePrimeNumbers.add(23);nextFivePrimeNumbers.add(29);// Adding an entire collection to an ArrayListfirstTenPrimeNumbers.addAll(nextFivePrimeNumbers);System.out.println(firstTenPrimeNumbers); }}
# Output
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
Accessing elements from an ArrayList
This example shows:
How to check if an ArrayList is empty using the isEmpty() method.
How to find the size of an ArrayList using the size() method.
How to access the element at a particular index in an ArrayList using the get() method.
How to modify the element at a particular index in an ArrayList using the set() method.
importjava.util.ArrayList;importjava.util.List;publicclassAccessElementsFromArrayListExample {publicstaticvoidmain(String[] args) {List<String> topCompanies =newArrayList<>();// Check if an ArrayList is emptySystem.out.println("Is the topCompanies list empty? : "+topCompanies.isEmpty());topCompanies.add("Google");topCompanies.add("Apple");topCompanies.add("Microsoft");topCompanies.add("Amazon");topCompanies.add("Facebook");// Find the size of an ArrayListSystem.out.println("Here are the top "+topCompanies.size() +" companies in the world");System.out.println(topCompanies);// Retrieve the element at a given indexString bestCompany =topCompanies.get(0);String secondBestCompany =topCompanies.get(1);String lastCompany =topCompanies.get(topCompanies.size() -1);System.out.println("Best Company: "+ bestCompany);System.out.println("Second Best Company: "+ secondBestCompany);System.out.println("Last Company in the list: "+ lastCompany);// Modify the element at a given indextopCompanies.set(4,"Walmart");System.out.println("Modified top companies list: "+ topCompanies); }}
# Output
Is the topCompanies list empty? : true
Here are the top 5 companies in the world
[Google, Apple, Microsoft, Amazon, Facebook]
Best Company: Google
Second Best Company: Apple
Last Company in the list: Facebook
Modified top companies list: [Google, Apple, Microsoft, Amazon, Walmart]
Removing elements from an ArrayList
This example shows:
How to remove the element at a given index in an ArrayList | remove(int index)
importjava.util.ArrayList;importjava.util.List;importjava.util.function.Predicate;publicclassRemoveElementsFromArrayListExample {publicstaticvoidmain(String[] args) {List<String> programmingLanguages =newArrayList<>();programmingLanguages.add("C");programmingLanguages.add("C++");programmingLanguages.add("Java");programmingLanguages.add("Kotlin");programmingLanguages.add("Python");programmingLanguages.add("Perl");programmingLanguages.add("Ruby");System.out.println("Initial List: "+ programmingLanguages);// Remove the element at index `5`programmingLanguages.remove(5);System.out.println("After remove(5): "+ programmingLanguages);// Remove the first occurrence of the given element from the ArrayList// (The remove() method returns false if the element does not exist in the ArrayList)boolean isRemoved =programmingLanguages.remove("Kotlin");System.out.println("After remove(\"Kotlin\"): "+ programmingLanguages);// Remove all the elements that exist in a given collectionList<String> scriptingLanguages =newArrayList<>();scriptingLanguages.add("Python");scriptingLanguages.add("Ruby");scriptingLanguages.add("Perl");programmingLanguages.removeAll(scriptingLanguages);System.out.println("After removeAll(scriptingLanguages): "+ programmingLanguages);// Remove all the elements that satisfy the given predicateprogrammingLanguages.removeIf(newPredicate<String>() { @Overridepublicbooleantest(String s) {returns.startsWith("C"); } });/* The above removeIf() call can also be written using lambda expression like this - programmingLanguages.removeIf(s -> s.startsWith("C")) */System.out.println("After Removing all elements that start with \"C\": "+ programmingLanguages);// Remove all elements from the ArrayListprogrammingLanguages.clear();System.out.println("After clear(): "+ programmingLanguages); }}
# Output
Initial List: [C, C++, Java, Kotlin, Python, Perl, Ruby]
After remove(5): [C, C++, Java, Kotlin, Python, Ruby]
After remove("Kotlin"): [C, C++, Java, Python, Ruby]
After removeAll(scriptingLanguages): [C, C++, Java]
After Removing all elements that start with "C": [Java]
After clear(): []
Iterating over an ArrayList
The following example shows how to iterate over an ArrayList using
importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;importjava.util.ListIterator;publicclassIterateOverArrayListExample {publicstaticvoidmain(String[] args) {List<String> tvShows =newArrayList<>();tvShows.add("Breaking Bad");tvShows.add("Game Of Thrones");tvShows.add("Friends");tvShows.add("Prison break");System.out.println("=== Iterate using Java 8 forEach and lambda ===");tvShows.forEach(tvShow -> {System.out.println(tvShow); });System.out.println("\n=== Iterate using an iterator() ===");Iterator<String> tvShowIterator =tvShows.iterator();while (tvShowIterator.hasNext()) {String tvShow =tvShowIterator.next();System.out.println(tvShow); }System.out.println("\n=== Iterate using an iterator() and Java 8 forEachRemaining() method ==="); tvShowIterator =tvShows.iterator();tvShowIterator.forEachRemaining(tvShow -> {System.out.println(tvShow); });System.out.println("\n=== Iterate using a listIterator() to traverse in both directions ===");// Here, we start from the end of the list and traverse backwards.ListIterator<String> tvShowListIterator =tvShows.listIterator(tvShows.size());while (tvShowListIterator.hasPrevious()) {String tvShow =tvShowListIterator.previous();System.out.println(tvShow); }System.out.println("\n=== Iterate using simple for-each loop ===");for(String tvShow: tvShows) {System.out.println(tvShow); }System.out.println("\n=== Iterate using for loop with index ===");for(int i =0; i <tvShows.size(); i++) {System.out.println(tvShows.get(i)); } }}
# Output
=== Iterate using Java 8 forEach and lambda ===
Breaking Bad
Game Of Thrones
Friends
Prison break
=== Iterate using an iterator() ===
Breaking Bad
Game Of Thrones
Friends
Prison break
=== Iterate using an iterator() and Java 8 forEachRemaining() method ===
Breaking Bad
Game Of Thrones
Friends
Prison break
=== Iterate using a listIterator() to traverse in both directions ===
Prison break
Friends
Game Of Thrones
Breaking Bad
=== Iterate using simple for-each loop ===
Breaking Bad
Game Of Thrones
Friends
Prison break
=== Iterate using for loop with index ===
Breaking Bad
Game Of Thrones
Friends
Prison break
The iterator() and listIterator() methods are useful when you need to modify the ArrayList while traversing.
Consider the following example, where we remove elements from the ArrayList using iterator.remove() method while traversing through it -
Check if an ArrayList contains a given element | contains()
Find the index of the first occurrence of an element in an ArrayList | indexOf()
Find the index of the last occurrence of an element in an ArrayList | lastIndexOf()
importjava.util.ArrayList;importjava.util.List;publicclassSearchElementsInArrayListExample {publicstaticvoidmain(String[] args) {List<String> names =newArrayList<>();names.add("John");names.add("Alice");names.add("Bob");names.add("Steve");names.add("John");names.add("Steve");names.add("Maria");// Check if an ArrayList contains a given elementSystem.out.println("Does names array contain \"Bob\"? : "+names.contains("Bob"));// Find the index of the first occurrence of an element in an ArrayListSystem.out.println("indexOf \"Steve\": "+names.indexOf("Steve"));System.out.println("indexOf \"Mark\": "+names.indexOf("Mark"));// Find the index of the last occurrence of an element in an ArrayListSystem.out.println("lastIndexOf \"John\" : "+names.lastIndexOf("John"));System.out.println("lastIndexOf \"Bill\" : "+names.lastIndexOf("Bill")); }}
Since ArrayList supports generics, you can create an ArrayList of any type. It can be of simple types like Integer, String, Double or complex types like an ArrayList of ArrayLists, or an ArrayList of HashMaps or an ArrayList of any user defined objects.
In the following example, you’ll learn how to create an ArrayList of user defined objects.
Sort an ArrayList of user defined objects with a custom comparator.
1. Sort an ArrayList using Collections.sort() method
importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;publicclassArrayListCollectionsSortExample {publicstaticvoidmain(String[] args) {List<Integer> numbers =newArrayList<>();numbers.add(13);numbers.add(7);numbers.add(18);numbers.add(5);numbers.add(2);System.out.println("Before : "+ numbers);// Sorting an ArrayList using Collections.sort() methodCollections.sort(numbers);System.out.println("After : "+ numbers); }}
# Output
Before : [13, 7, 18, 5, 2]
After : [2, 5, 7, 13, 18]
2. Sort an ArrayList using ArrayList.sort() method
importjava.util.ArrayList;importjava.util.Comparator;importjava.util.List;publicclassArrayListSortExample {publicstaticvoidmain(String[] args) {List<String> names =newArrayList<>();names.add("Lisa");names.add("Jennifer");names.add("Mark");names.add("David");System.out.println("Names : "+ names);// Sort an ArrayList using its sort() method. You must pass a Comparator to the ArrayList.sort() method.names.sort(newComparator<String>() { @Overridepublicintcompare(String name1,String name2) {returnname1.compareTo(name2); } });// The above `sort()` method call can also be written simply using lambda expressionnames.sort((name1, name2) ->name1.compareTo(name2));// Following is an even more concise solutionnames.sort(Comparator.naturalOrder());System.out.println("Sorted Names : "+ names); }}
3. Sort an ArrayList of Objects using custom Comparator
importjava.util.ArrayList;importjava.util.Collections;importjava.util.Comparator;importjava.util.List;classPerson {privateString name;privateInteger age;publicPerson(String name,Integer age) {this.name= name;this.age= age; }publicStringgetName() {return name; }publicvoidsetName(String name) {this.name= name; }publicIntegergetAge() {return age; }publicvoidsetAge(Integer age) {this.age= age; } @OverridepublicStringtoString() {return"{"+"name='"+ name +'\''+", age="+ age +'}'; }}publicclassArrayListObjectSortExample {publicstaticvoidmain(String[] args) {List<Person> people =newArrayList<>();people.add(newPerson("Sachin",47));people.add(newPerson("Chris",34));people.add(newPerson("Rajeev",25));people.add(newPerson("David",31));System.out.println("Person List : "+ people);// Sort People by their Agepeople.sort((person1, person2) -> {returnperson1.getAge() -person2.getAge(); });// A more concise way of writing the above sorting functionpeople.sort(Comparator.comparingInt(Person::getAge));System.out.println("Sorted Person List by Age : "+ people);// You can also sort using Collections.sort() method by passing the custom ComparatorCollections.sort(people,Comparator.comparing(Person::getName));System.out.println("Sorted Person List by Name : "+ people); }}
# Output
Person List : [{name='Sachin', age=47}, {name='Chris', age=34}, {name='Rajeev', age=25}, {name='David', age=31}]
Sorted Person List by Age : [{name='Rajeev', age=25}, {name='David', age=31}, {name='Chris', age=34}, {name='Sachin', age=47}]
Sorted Person List by Name : [{name='Chris', age=34}, {name='David', age=31}, {name='Rajeev', age=25}, {name='Sachin', age=47}]
Synchronizing Access to an ArrayList
The ArrayList class is not synchronized. If multiple threads try to modify an ArrayList at the same time then the final result becomes not-deterministic because one thread might override the changes done by another thread.
Example Demonstrating ArrayList’s unpredictable behavior in multi-threaded environments
The following example shows what happens when multiple threads try to modify an ArrayList at the same time.
importjava.util.ArrayList;importjava.util.List;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.TimeUnit;publicclassUnsafeArrayListExample {publicstaticvoidmain(String[] args) throwsInterruptedException {List<Integer> unsafeArrayList =newArrayList<>();unsafeArrayList.add(1);unsafeArrayList.add(2);unsafeArrayList.add(3);// Create a thread pool of size 10ExecutorService executorService =Executors.newFixedThreadPool(10);// Create a Runnable task that increments each element of the ArrayList by oneRunnable task = () -> {incrementArrayList(unsafeArrayList); };// Submit the task to the executor service 100 times.// All the tasks will modify the ArrayList concurrentlyfor(int i =0; i <100; i++) {executorService.submit(task); }executorService.shutdown();executorService.awaitTermination(60,TimeUnit.SECONDS);System.out.println(unsafeArrayList); }// Increment all the values in the ArrayList by oneprivatestaticvoidincrementArrayList(List<Integer> unsafeArrayList) {for(int i =0; i <unsafeArrayList.size(); i++) {Integer value =unsafeArrayList.get(i);unsafeArrayList.set(i, value +1); } }}
The final output of the above program should be equal to [101, 102, 103] because we’re incrementing the values in the ArrayList 100 times. But if you run the program, it will produce different output every time it is run -
# Output
[96, 96, 98]
Try running the above program multiple times and see how it produces different outputs. To learn more about such issues in multi-threaded programs, check out my article on Java Concurrency Issues and Thread Synchronization.
Example demonstrating how to synchronize concurrent modifications to an ArrayList
All right! Now let’s see how we can synchronize access to the ArrayList in multi-threaded environments.
The following example shows the synchronized version of the previous example. Unlike the previous program, the output of this program is deterministic and will always be the same.
importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;importjava.util.concurrent.ExecutorService;importjava.util.concurrent.Executors;importjava.util.concurrent.TimeUnit;publicclassSynchronizedArrayListExample {publicstaticvoidmain(String[] args) throwsInterruptedException {List<Integer> safeArrayList =Collections.synchronizedList(newArrayList<>());safeArrayList.add(1);safeArrayList.add(2);safeArrayList.add(3);// Create a thread pool of size 10ExecutorService executorService =Executors.newFixedThreadPool(10);// Create a Runnable task that increments each element of the ArrayList by oneRunnable task = () -> {incrementArrayList(safeArrayList); };// Submit the task to the executor service 100 times.// All the tasks will modify the ArrayList concurrentlyfor(int i =0; i <100; i++) {executorService.submit(task); }executorService.shutdown();executorService.awaitTermination(60,TimeUnit.SECONDS);System.out.println(safeArrayList); }// Increment all the values in the ArrayList by oneprivatestaticvoidincrementArrayList(List<Integer> safeArrayList) {synchronized (safeArrayList) {for (int i =0; i <safeArrayList.size(); i++) {Integer value =safeArrayList.get(i);safeArrayList.set(i, value +1); } } }}
Moreover, the modifications to the ArrayList inside the incrementArrayList() method is wrapped inside a synchronized block. This ensures that no two threads can increment ArrayList elements at the same time.
You can also use a CopyOnWriteArrayList if you need thread safety. It is a thread-safe version of the ArrayList class. It implements all the mutating operations by making a fresh copy of the ArrayList.
More Examples :
Example a: Add an element to specified index of Java ArrayList Example
/* Add an element to specified index of Java ArrayList Example This Java Example shows how to add an element at specified index of java ArrayList object using add method.*/importjava.util.ArrayList;publicclassAddElementToSpecifiedIndexArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add("1");arrayList.add("2");arrayList.add("3");/* To add an element at the specified index of ArrayList use void add(int index, Object obj) method. This method inserts the specified element at the specified index in the ArrayList. */arrayList.add(1,"INSERTED ELEMENT");/* Please note that add method DOES NOT overwrites the element previously at the specified index in the list. It shifts the elements to right side and increasing the list size by 1. */System.out.println("ArrayList contains...");//display elements of ArrayListfor(int index=0; index <arrayList.size(); index++)System.out.println(arrayList.get(index)); }}/*Output would beArrayList contains...1INSERTED ELEMENT23*/
Example b: Get Size of Java ArrayList and loop through elements Example
/* Get Size of Java ArrayList and loop through elements Example This Java Example shows how to get size or number of elements currently stored in ArrayList. It also shows how to loop through element of it.*/importjava.util.ArrayList;publicclassGetSizeOfArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to Arraylist usingarrayList.add("1");arrayList.add("2");arrayList.add("3");//To get size of Java ArrayList use int size() methodint totalElements =arrayList.size();System.out.println("ArrayList contains...");//loop through itfor(int index=0; index < totalElements; index++)System.out.println(arrayList.get(index)); }}/*Output would beArrayList contains...123*/
Example c: Search an element of Java ArrayList Example
/* Search an element of Java ArrayList Example This Java Example shows how to search an element of java ArrayList object using contains, indexOf and lastIndexOf methods.*/importjava.util.ArrayList;publicclassSearchAnElementInArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add("1");arrayList.add("2");arrayList.add("3");arrayList.add("4");arrayList.add("5");arrayList.add("1");arrayList.add("2");/* To check whether the specified element exists in Java ArrayList use boolean contains(Object element) method. It returns true if the ArrayList contains the specified objct, false otherwise. */boolean blnFound =arrayList.contains("2");System.out.println("Does arrayList contain 2 ? "+ blnFound);/* To get an index of specified element in ArrayList use int indexOf(Object element) method. This method returns the index of the specified element in ArrayList. It returns -1 if not found. */int index =arrayList.indexOf("4");if(index ==-1)System.out.println("ArrayList does not contain 4");elseSystem.out.println("ArrayList contains 4 at index :"+ index);/* To get last index of specified element in ArrayList use int lastIndexOf(Object element) method. This method returns index of the last occurrence of the specified element in ArrayList. It returns -1 if not found. */int lastIndex =arrayList.lastIndexOf("1");if(lastIndex ==-1)System.out.println("ArrayList does not contain 1");elseSystem.out.println("Last occurrence of 1 in ArrayList is at index :"+ lastIndex); } }/*Output would beDoes arrayList contain 2 ? trueArrayList contains 4 at index :3Last occurrence of 1 in ArrayList is at index :5*/
Example d: Get Sub List of Java ArrayList Example
*GetSubList of JavaArrayListExampleThisJavaExample shows how to get sub list of java ArrayList using subList method by providing start and end index.*/importjava.util.ArrayList;importjava.util.List;publicclassGetSubListOfJavaArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add("1");arrayList.add("2");arrayList.add("3");arrayList.add("4");arrayList.add("5");/* To get a sub list of Java ArrayList use List subList(int startIndex, int endIndex) method. This method returns an object of type List containing elements from startIndex to endIndex - 1. */List lst =arrayList.subList(1,3);//display elements of sub list.System.out.println("Sub list contains : ");for(int i=0; i<lst.size() ; i++)System.out.println(lst.get(i));/* Sub List returned by subList method is backed by original Arraylist. So any changes made to sub list will also be REFLECTED in the original Arraylist. *///remove one element from sub listObject obj =lst.remove(0);System.out.println(obj +" is removed from sub list");//print original ArrayListSystem.out.println("After removing "+ obj +" from sub list, original ArrayList contains : ");for(int i=0; i<arrayList.size() ; i++)System.out.println(arrayList.get(i)); }}/*Output would beSub list contains :232 is removed from sub listAfter removing 2 from sub list original ArrayList contains :1345*/
Example e: Remove an element from specified index of Java ArrayList
/* Remove an element from specified index of Java ArrayList Example This Java Example shows how to remove an element at specified index of java ArrayList object using remove method.*/importjava.util.ArrayList;publicclassRemoveElementFromArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add("1");arrayList.add("2");arrayList.add("3");/* To remove an element from the specified index of ArrayList use Object remove(int index) method. It returns the element that was removed from the ArrayList. */Object obj =arrayList.remove(1);System.out.println(obj +" is removed from ArrayList");System.out.println("ArrayList contains...");//display elements of ArrayListfor(int index=0; index <arrayList.size(); index++)System.out.println(arrayList.get(index)); }}/*Output would be2 is removed from ArrayListArrayList contains...13*/
Example f: Sort elements of Java ArrayList
/* Sort elements of Java ArrayList Example This Java Example shows how to sort the elements of java ArrayList object using Collections.sort method.*/importjava.util.ArrayList;importjava.util.Collections;publicclassSortJavaArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add("1");arrayList.add("3");arrayList.add("5");arrayList.add("2");arrayList.add("4");/* To sort an ArrayList object, use Collection.sort method. This is a static method. It sorts an ArrayList object's elements into ascending order. */Collections.sort(arrayList);//display elements of ArrayListSystem.out.println("ArrayList elements after sorting in ascending order : ");for(int i=0; i<arrayList.size(); i++)System.out.println(arrayList.get(i)); }}/*Output would beArrayList elements after sorting in ascending order :12345*/
Example 1:
packagecom.bb.ilp.tests;importjava.util.ArrayList;importjava.util.Iterator;importcom.bb.ilp.beans.Author;importcom.bb.ilp.beans.Book;publicclassSMSTest {publicstaticvoidmain(String[] args) {Book book1 =newBook(1,"Algorithms by ex","ADA","Cormen");Book book2 =newBook(2,"Data Structures made easy","Data structures","Hewitt");Book book3 =newBook(3,"Java Complete reference","Java","Herbert shield");Author author1 =newAuthor(1,"Cormen", (byte) 26,"Sec 31 ggn", book1);Author author2 =newAuthor(2,"Rahul", (byte) 27,"Sec 17 punjab", book2);Author author3 =newAuthor(3,"Herbert shield", (byte) 35,"Sec 14 delhi", book3);//creating Arraylist of BookArrayList<Book> listOfBooks =newArrayList<>();//add()//Add elements== Object of book type using .add()listOfBooks.add(book1);listOfBooks.add(book2);listOfBooks.add(book3);//get()//Accessing book object using get() starting with index 0System.out.println(listOfBooks.get(0).getBookId());System.out.println(listOfBooks.get(1).getBookId());System.out.println(listOfBooks.get(2).getBookId());//get() using loop//enhancing above code by using for loopfor(int i=0;i<listOfBooks.size();i++) {System.out.println(listOfBooks.get(i).getBookId()); }//get using advanced loop//using for-each loopfor(Book book:listOfBooks) {System.out.println(book.getBookId()); }//get using iteratorIterator<Book> iterator=listOfBooks.iterator();while(iterator.hasNext()) {System.out.println(iterator.next().getBookId()); }//removing book with id 2 from the list//always use iterator for doing soIterator<Book> iteratorToRemove=listOfBooks.iterator();while(iteratorToRemove.hasNext()) {if(iteratorToRemove.next().getBookId()==2) {iteratorToRemove.remove(); } }//isEmpty()boolean isEmpty=listOfBooks.isEmpty();if(isEmpty) {System.out.println("List is empty"); }else {System.out.println("List is not empty"); }//size()int size=listOfBooks.size();System.out.println("Size of listOfBooks is "+size);//contains() , to check whether the list contains our bookif(listOfBooks.contains(book1)) {System.out.println("yes it contains"); }else {System.out.println("no it doesn't"); }//clear is used to remove all the elementslistOfBooks.clear();//now check the whether it is cleared or not by checking size or isEmptyif(listOfBooks.isEmpty()) {System.out.println("List is empty"); }else {System.out.println("List is not empty"); } }}
1
2
3
1
2
3
1
2
3
1
2
3
List is not empty
Size of listOfBooks is 2
yes it contains
List is empty
Example 2:
packagecom;importjava.util.ArrayList;importjava.util.Arrays;importjava.util.List;/** * Java ArrayList Example Program * * @author Mohit * */publicclassTest {publicstaticvoidmain(String args[]) {List<String> letters =newArrayList<String>();// add exampleletters.add("A");letters.add("C");letters.add("D");// let's insert B between A and Cletters.add(1,"B");System.out.println(letters);List<String> list =newArrayList<String>();list.add("E");list.add("H");// appending list elements to lettersletters.addAll(list);System.out.println(letters);// clear example to empty the listlist.clear();list.add("F");list.add("G");// inserting list inside letters to get right sequenceletters.addAll(5, list);System.out.println(letters);// contains exampleSystem.out.println("Letters list contains E ? "+letters.contains("E"));System.out.println("Letters list contains Z ? "+letters.contains("Z"));// ensureCapacity example, it's ArrayList method, so object should be defined// like below.ArrayList<String> tempList =newArrayList<>();tempList.ensureCapacity(1000);// get exampleString e =letters.get(4);System.out.println("Letter at 5th place: "+ e);// tempList is empty?System.out.println("tempList is empty ? "+tempList.isEmpty());// indexOf exampleSystem.out.println("First index of D = "+letters.indexOf("D"));System.out.println("Last index of D = "+letters.lastIndexOf("D"));// remove examplesSystem.out.println(letters);String removed =letters.remove(3);System.out.println("After removing '"+ removed +"' letters contains "+ letters);// remove first occurrence of Hboolean isRemoved =letters.remove("H");System.out.println("H removed? "+ isRemoved +". Letters contains "+ letters);System.out.println("list contains "+ list);// remove all matching elements between letters and listletters.removeAll(list);System.out.println(letters);// retainAll examplelist.clear();list.add("A");list.add("B");list.add("C");letters.retainAll(list);System.out.println("letters elements after retainAll operation: "+ letters);// size exampleSystem.out.println("letters ArrayList size = "+letters.size());// set exampleletters.set(2,"D");System.out.println(letters);// toArray exampleString[] strArray =newString[letters.size()]; strArray =letters.toArray(strArray);System.out.println(Arrays.toString(strArray)); }}
[A, B, C, D]
[A, B, C, D, E, H]
[A, B, C, D, E, F, G, H]
Letters list contains E ? true
Letters list contains Z ? false
Letter at 5th place: E
tempList is empty ? true
First index of D = 3
Last index of D = 3
[A, B, C, D, E, F, G, H]
After removing 'D' letters contains [A, B, C, E, F, G, H]
H removed? true. Letters contains [A, B, C, E, F, G]
list contains [F, G]
[A, B, C, E]
letters elements after retainAll operation: [A, B, C]
letters ArrayList size = 3
[A, B, D]
[A, B, D]
Java ArrayList Iterator
Iterator is an interface in Java Collections framework. ArrayList provides fail-fast iterator implementation. When you want to perform some operation on all the list elements, you should use Iterator. If any structural modification is made to the list while iterating, it’s next() operation will throw ConcurrentModificationException. Below is a simple example of ArrayList iterator.
Example 3:
packagecom;importjava.util.ArrayList;importjava.util.Iterator;importjava.util.List;/** * Java ArrayList Example Program * * @author Mohit * */publicclassTest {publicstaticvoidmain(String args[]) {List<Integer> ints =newArrayList<>();for (int i =0; i <10; i++) {ints.add(i); }Iterator<Integer> it =ints.iterator();// simple iterationwhile (it.hasNext()) {int x = (int) it.next();System.out.print(x +", "); }System.out.println("\n"+ ints);// modification of list through iterator it =ints.iterator();while (it.hasNext()) {int x = (int) it.next();if (x %2==0) {it.remove(); } }System.out.println(ints);// changing list structure while iterating it =ints.iterator();while (it.hasNext()) {int x = (int) it.next(); // ConcurrentModificationException hereif (x ==5) {ints.add(20); } } }}
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 3, 5, 7, 9]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909)
at java.util.ArrayList$Itr.next(ArrayList.java:859)
at com.Test.main(Test.java:42)
Example 4: Copy elements from one arraylist to another:
/* Copy Elements of One Java ArrayList to Another Java ArrayList Example This java example shows how to copy all elements of one Java ArrayList object to another Java ArrayList object using copy method of Collections class.*/importjava.util.ArrayList;importjava.util.Collections;publicclassCopyElementsOfArrayListToArrayListExample {publicstaticvoidmain(String[] args) {//create first ArrayList objectArrayList arrayList1 =newArrayList();//Add elements to ArrayListarrayList1.add("1");arrayList1.add("2");arrayList1.add("3");//create another ArrayList objectArrayList arrayList2 =newArrayList();//Add elements to ArraylistarrayList2.add("One");arrayList2.add("Two");arrayList2.add("Three");arrayList2.add("Four");arrayList2.add("Five");/* To copy elements of one Java ArrayList to another use, static void copy(List dstList, List sourceList) method of Collections class. This method copies all elements of source list to destination list. After copy index of the elements in both source and destination lists would be identical. The destination list must be long enough to hold all copied elements. If it is longer than that, the rest of the destination list's elments would remain unaffected. */System.out.println("Before copy, Second ArrayList Contains : "+ arrayList2);//copy all elements of ArrayList to another ArrayList using copy //method of Collections classCollections.copy(arrayList2,arrayList1);/* Please note that, If destination ArrayList object is not long enough to hold all elements of source ArrayList, it throws IndexOutOfBoundsException. */System.out.println("After copy, Second ArrayList Contains : "+ arrayList2); }}/*Output would beBefore copy, Second ArrayList Contains : [One, Two, Three, Four, Five]After copy, Second ArrayList Contains : [1, 2, 3, Four, Five]*/
Example 5: Find maximum element of Java ArrayList.
/* Find maxmimum element of Java ArrayList Example This java example shows how to find a maximum element of Java ArrayList using max method of Collections class.*/importjava.util.ArrayList;importjava.util.Collections;publicclassFindMaximumOfArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add(newInteger("327482"));arrayList.add(newInteger("13408"));arrayList.add(newInteger("802348"));arrayList.add(newInteger("345308"));arrayList.add(newInteger("509324"));/* To find maximum element of Java ArrayList use, static Object max(Collection c) method of Collections class. This method returns the maximum element of Java ArrayList according to its natural ordering. */Object obj =Collections.max(arrayList);System.out.println("Maximum Element of Java ArrayList is : "+ obj); }}/*Output would beMaximum Element of Java ArrayList is : 802348*/
Example 6: Find Minimum element of Java ArrayList
/* Find Minimum element of Java ArrayList Example This java example shows how to find a minimum element of Java ArrayList using min method of Collections class.*/importjava.util.ArrayList;importjava.util.Collections;publicclassFindMinimumOfArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add(newInteger("327482"));arrayList.add(newInteger("13408"));arrayList.add(newInteger("802348"));arrayList.add(newInteger("345308"));arrayList.add(newInteger("509324"));/* To find minimum element of Java ArrayList use, static Object min(Collection c) method of Collections class. This method returns the minimum element of Java ArrayList according to its natural ordering. */Object obj =Collections.min(arrayList);System.out.println("Minimum Element of Java ArrayList is : "+ obj); }}/*Output would beMinimum Element of Java ArrayList is : 13408*/
Example 7: Swap elements of Java ArrayList
/* Swap elements of Java ArrayList example This java example shows how to swap elements of Java ArrayList object using swap method of Collections class.*/importjava.util.ArrayList;importjava.util.Collections;publicclassSwapElementsOfArrayListExample {publicstaticvoidmain(String[] args) {//create an ArrayList objectArrayList arrayList =newArrayList();//Add elements to ArraylistarrayList.add("A");arrayList.add("B");arrayList.add("C");arrayList.add("D");arrayList.add("E");System.out.println("Before swaping, ArrayList contains : "+ arrayList);/* To swap elements of Java ArrayList use, static void swap(List list, int firstElement, int secondElement) method of Collections class. Where firstElement is the index of first element to be swapped and secondElement is the index of the second element to be swapped. If the specified positions are equal, list remains unchanged. Please note that, this method can throw IndexOutOfBoundsException if any of the index values is not in range. */Collections.swap(arrayList,0,4);System.out.println("After swaping, ArrayList contains : "+ arrayList); }}/*Output would beBefore swaping, ArrayList contains : [A, B, C, D, E]After swaping, ArrayList contains : [E, B, C, D, A]*/