1. Introduction
This article is part of Complete Guide to ArrayList series. In this article, we will discuss how to add/set/get elements in/from the ArrayList with several examples.
2. Content
Below are 6 different methods that I will discuss.
public boolean add(E e) public void add(int index, E element) public boolean addAll(Collection<? extends E> c) public boolean addAll(int index, Collection<? extends E> c) public E get(int index) E set(int index, E element) List<E> subList(int fromIndex, int toIndex) boolean retainAll(Collection<?> c)
3. public boolean add(E e)
add(E e) method is used to insert an element into an ArrayList. The add(E e) method is used to append an element to the List. After the successful insertion of the element into ArrayList, this method returns true.
Example :
List<String> names = new ArrayList<>(); names.add("John");
If ArrayList cannot insert the element, i.e. if the memory is less than the number of elements we are trying to add, then we get a runtime exception called OutOfMemoryError.
Below example shows, I am trying to add 1 billion elements to ArrayList.
List<String> names = new ArrayList<>(); for (int i = 0; i < 1_000_000_000; i++) { try { names.add("John"); } catch (Throwable e) { System.out.println("index : " + i); names.clear(); e.printStackTrace(); } } index : 798381090 java.lang.OutOfMemoryError: Java heap space at java.base/java.util.Arrays.copyOf(Arrays.java:3511) at java.base/java.util.Arrays.copyOf(Arrays.java:3480) at java.base/java.util.ArrayList.grow(ArrayList.java:236) at java.base/java.util.ArrayList.grow(ArrayList.java:243) at java.base/java.util.ArrayList.add(ArrayList.java:453) at java.base/java.util.ArrayList.add(ArrayList.java:466)
You can add a maximum of 2147483639 elements in ArrayList. So why did my test fail at 798381090? Because the heap size of my JVM is less than the required heap size.
4. public void add(int index, E element)
add(int index, E element) method is used to add an element at specific index. ArrayList shifts all the elements on the right side of this index by one place, i.e. their index is increments by 1. If the index is not in range i.e. < 0 or > size of ArrayList, then ArrayList throws IndexOutOfBoundsException.
List<String> names = new ArrayList<>(); names.add("John"); names.add("Jane"); names.add(null); names.add(3, "Sansa"); System.out.println(names); Output : [John, Jane, null, Sansa]
List<String> names = new ArrayList<>(); names.add("John"); names.add("Jane"); names.add(null); names.add(1, "Sansa"); System.out.println(names); Output : [John, Sansa, Jane, null]
5. public boolean addAll(Collection<? extends E> c)
addAll(Collection<? extends E> c) method is used to append all the elements of this Collection into an ArrayList. The sequence in which elements are added to ArrayList depends on the specified Collection’s iterator. This method will throw a NullPointerException if the Collection is null. This method returns true if elements were successfully inserted in ArrayList.
List<String> names1 = new ArrayList<>(); names1.add("John"); names1.add("Jane"); List<String> names2 = new ArrayList<>(); names2.add("Doe"); names2.add("Dane"); // names2 is appended. throws NPE if names2 is null. names1.addAll(names2); System.out.println(names1); Output : [John, Jane, Doe, Dane]
6. public boolean addAll(int index, Collection<? extends E> c)
addAll(int index, Collection<? extends E> c) method is similar to add(int index, E element) method. The only difference is instead of adding a single element, we will insert the entire Collection as part of this call. This method returns true if elements are successfully inserted in ArrayList.
If the input Collection is not empty and not null then all the elements after this index are shifted by this Collection’s size. If the index is not in range i.e. < 0 or > size of ArrayList, then ArrayList throws IndexOutOfBoundsException.
List<String> names1 = new ArrayList<>(); names1.add("John"); names1.add("Jane"); List<String> names2 = new ArrayList<>(); names2.add("Doe"); names2.add("Dane"); names1.addAll(0, names2); System.out.println(names1); Output : [Doe, Dane, John, Jane]
7. public E get(int index)
get(int index) method is used to get an element from an index. If the index is not in range i.e. < 0 or >= size of ArrayList, then ArrayList throws IndexOutOfBoundsException.
List<String> names = new ArrayList<>(); names.add("John"); names.add("Jane"); String str = names.get(1); System.out.println("element at index " + index + " is " + str); Output : Jane
8. E set(int index, E element)
set(int index, E element) method is used to replace the element at specific index. Set method returns the previous element at this index. If the index is not in range i.e. < 0 or >= size of ArrayList, then ArrayList throws IndexOutOfBoundsException.
List<String> names = new ArrayList<>(); names.add("John"); names.add("Jane"); int index = 1; names.set(index, "Arya"); System.out.println(names); Output : [John, Arya]
9. List<E> subList(int fromIndex, int toIndex)
subList(int fromIndex, int toIndex) method is used to return the partial List from the fromIndex(inclusive) till toIndex(exclusive). Inclusive means that index is considered and exclusive means that index-1 is taken into account
For example :
fromIndex = 5
toIndex = 9
Returned List<> will be from index 5, 6, 7 and 8. Index 9 won’t be taken into account.
List<String> names = new ArrayList<>(); names.add("Jon"); names.add("Sansa"); names.add("Arya"); names.add("Rickon"); names.add("Bran"); List<String> sublist = names.subList(1, 3); System.out.println(sublist); Output : [Sansa, Arya]
The returned List is a view of the original List. So it does not create a new ArrayList. It just returns the backing ArrayList with new bounds. Any changes to sublist reflects in original ArrayList and vice versa.
10. boolean retainAll(Collection<?> c)
retainAll(Collection<?> c) method is used to retain the elements that contained in specified Collection. It means that remove all the elements from ArrayList are not in this Collection.
Let us understand this with examples :
Example 1 : retain names Jack and Jane from the names1 List.
List<String> names1 = new ArrayList<>(); names1.add("John"); names1.add("Jane"); names1.add("Jack"); List<String> names2 = new ArrayList<>(); names2.add("Jack"); names2.add("Jane"); names1.retainAll(names2); Output : [Jane, Jack]
Example 2 : retain name Jack from the names1 List. I repeat the name Jack multiple times, but it doesn’t matter as ArrayList allows repetition(duplication) of elements.
List<String> names1 = new ArrayList<>(); names1.add("John"); names1.add("Jane"); names1.add("Jack"); List<String> names2 = new ArrayList<>(); names2.add("Jack"); names2.add("Jack"); names2.add("Jack"); names1.retainAll(names2); Output: [Jack]
Example 3 : retain name Jack from the names1 List. I repeat the name Jack multiple times, but it doesn’t matter as ArrayList allows repetition(duplication) of elements.
List<String> names1 = new ArrayList<>(); names1.add("John"); names1.add("Jane"); names1.add("Jack"); List<String> names2 = new ArrayList<>(); names2.add("Sansa"); names2.add("Arya"); names1.retainAll(names2); Output : []
11. Conclusion
That is all on adding, setting and getting elements from ArrayList. In the next article, we will see how to remove elements from ArrayList.