ArrayList is a part of collection framework and is present in java.util package. It provides us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed.
The ArrayList class extends AbstractList class and implements the List interface.
ArrayList is a generic class that has this declaration:
Here, E specifies the type of objects that the list will hold.
- ArrayList inherits AbstractList class and implements List interface.
- ArrayList is default size is 10. The size can increase if collection grows or shrunk if objects are removed from the collection.
- ArrayList allows us to randomly access the list.
- Manupulation in ArrayList is slow, because lots of shifting needs to be occurred if any element is removed/deleted from the array list.
- ArrayList can not be used for primitive types, like int, char, etc. We need to use wrapper classes.
- ArrayList class can contain duplicate elements.
- ArrayList class maintains insertion order.
- Java ArrayList is not synchronized.
- Java ArrayList is roughly equivalent to Vector, except that it is unsynchronized.
- The iterators return by java ArrayList's Iterator() and listIterator () methods are fail-fast. If the list structure is modified after creating the iterator in any other way except the iterator add or remove methods, it will throw ConcurrentModificationException.
Java ArrayList constructors
There are three constructors in Java ArrayList.
Constructor | Description |
---|---|
public ArrayList(int initialCapacity) | This ArrayList constructor will return an empty list with initial capacity as specified by the initialCapacity argument. This constructor is useful when you know that your list will contain huge data and you want to save time of reallocation by providing a large value of initial capacity. If the initialCapacity argument is negative, it will throw IllegalArgumentException. |
public ArrayList() | Most widly used Java ArrayList constructor.This constructor will return an empty list with initial capacity of 10. |
public ArrayList(Collection<? extends E> c) | This Java ArrayList constructor return a list containing the elements of the specified collection c, in the order they are returned by the collection's iterator. It will throws NullPointerException if the specified collection c is null |
Below is a simple code snippet showing Java ArrayList constructors.
// Java ArrayList default constructor Listnames = new ArrayList (); // Java ArrayList constructor with initial capacity List dictonaryWords = new ArrayList (10000); // creating a list from the existing collection List nameList = new ArrayList (names);
Java ArrayList methods
Method | Description |
---|---|
public int size() | Returns the number of elements in the invoking list. |
public boolean isEmpty() | Returns true if the invoking list contains no elements. |
public boolean contains(Object obj) | Returns true if the invoking list contains the specified element. |
public int indexOf(Object obj) | Returns the index of the first occurrence of the specified element in the invoking list, or -1 if the invoking list does not contain the element. |
public int lastIndexOf(Object obj) | Returns the index of the last occurrence of the specified element in the invoking list, or -1 if the invoking list does not contain the element. |
public Object clone() | Returns a shallow copy of the invoking ArrayList instance.(The elements themselves are not copied.) |
public Object[] toArray() | Returns an array containing all of the elements in the invoking list in proper sequence (from first to last element). The returned array will be "safe" in that no references to it are maintained by this list. (In other words, this method must allocate a new array). The caller is thus free to modify the returned array. |
public <T> T[] toArray(T[] arr) | Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list. |
public E get(int index) | Returns the element at the specified position in this list. |
public E set(int index, E element) | Replaces the element at the specified position in this list with the specified element. |
public boolean add(E e) | Appends the specified element e to the end of this list. |
public void add(int index, E element) | Inserts the specified element at the specified position in this list. Shifts the element currently at that position (if any) and any subsequent elements to the right. If index is greater than list size or negative, it will throw IndexOutOfBoundsException. |
public E remove(int index) | Removes the element at the specified position in this list. Shifts any subsequent elements to the left. If index is greater than list size or negative, it will throw IndexOutOfBoundsException. |
public boolean remove(Object obj) | Removes the first occurrence of the specified element from this list, if it is present. If the list does not contain the element, it is unchanged. |
public void clear() | Removes all of the elements from this list. The list will be empty after this call returns. |
public boolean addAll(Collection<? extends E> c) | Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behavior of this operation is undefined if the specified collection is modified while the operation is in progress. This method also throws NullPointerException if specified collection is null. |
public boolean addAll(int index, Collection<? extends E> c) | Inserts all of the elements in the specified collection into this list, starting at the specified position. Shifts the element currently at that position (if any) and any subsequent elements to the right (increases their indices). This method will throw IndexOutOfBoundsException if the index value is greater than list size or negative. This method also throws NullPointerException if specified collection is null. |
protected void removeRange(int fromIndex, int toIndex) | Removes all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive from this list. Shifts any succeeding elements to the left (reduces their index). This method will throw IndexOutOfBoundsException if fromIndex or toIndex is out of range ( fromIndex < 0 || fromIndex >= size() || toIndex > size() || toIndex < fromIndex). |
public boolean removeAll(Collection< ? > c) | Removes from this list all of its elements that are contained in the specified collection. |
public boolean retainAll(Collection< ? > c) | Retains only the elements in this list that are contained in the specified collection. In other words, removes from this list all of its elements that are not contained in the specified collection. |
public ListIterator<E> listIterator(int index) | Returns a list iterator over the elements in this list (in proper sequence), starting at the specified position in the list. The specified index indicates returned by an initial call to next. An initial call to previous would return the element with the specified index minus one. This method throws IndexOutOfBoundsException if index value is greater than or equal to list size or negative. |
public ListIterator<E> listIterator() | Returns a list iterator over the elements in this list. |
public Iterator<E> iterator() | Returns an iterator over the elements in this list in proper sequence. |
public List<E> subList(int fromIndex, int toIndex) | Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. The returned list is backed by this list, so non-structural changes in the returned list are reflected in this list, and vice-versa. |
public Spliterator<E> spliterator() | Creates a late-binding and fail-fast Spliterator over the elements in this list. |
public boolean removeIf(Predicate<? super E> filter) | Removes all of the elements of this collection that satisfy the given predicate. |
public void replaceAll(UnaryOperator<E> operator) | Replaces each element of this list with the result of applying the operator to that element. |
public void sort(Comparator<? super E> c) | Sorts this list according to the order induced by the specified Comparator. |
public void forEach(Consumer<? super E> action) | Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. |
public void ensureCapacity(int minCapacity) | Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument. |
public void trimToSize() | Trims the capacity of this ArrayList instance to be the list's current size. An application can use this operation to minimize the storage of an ArrayList instance. |
Java ArrayList Example
Java ArrayList common operations
Here we will see an example of commonly used method of ArrayList.
package com.walking.techie; import java.util.ArrayList; import java.util.List; public class ArrayListDemo { public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); // Add elements in ArrayList numbers.add(10); numbers.add(20); numbers.add(30); System.out.println("Elements of numbers list " + numbers); // Lets add 14 at specified position numbers.add(1, 15); System.out.println("Elements of numbers list " + numbers); // size of array list numbers System.out.println("Size of numbers list is " + numbers.size()); // get operation of array list System.out.println("Element in numbers at 1st position is " + numbers.get(1)); // check array list numbers contain 20 System.out.println("numbers list contain element 20 ?: " + numbers.contains(20)); // check index of 20 in the array list numbers, -1 will return if not // present in list System.out.println("Index of 15 in numbers list is " + numbers.indexOf(20)); // creating odd numbers list List<Integer> oddNumbers = new ArrayList<Integer>(); oddNumbers.add(5); oddNumbers.add(25); oddNumbers.add(9); // appending odd numbers list to numbers list numbers.addAll(oddNumbers); System.out.println("numbers list after appending odd numbers list " + numbers); // clear method to empty the odd numbers list oddNumbers.clear(); System.out.println("odd number list " + oddNumbers); // set method example numbers.set(1, 40); System.out.println("numbers list " + numbers); // remove method, to remove element of list from 1st index numbers.remove(1); System.out.println("numbers list after removing 40 " + numbers); // remove first occurrence of 5 boolean isRemoved = numbers.remove(new Integer(5)); System.out.println("element 5 removed ? " + isRemoved + " numbers contains " + numbers); // removeAll example oddNumbers.add(13); oddNumbers.add(25); oddNumbers.add(9); numbers.removeAll(oddNumbers); System.out.println("numbers elements after removeAll call " + numbers); numbers.add(25); numbers.add(9); // retainAll example oddNumbers.add(25); oddNumbers.add(11); oddNumbers.add(9); numbers.retainAll(oddNumbers); System.out.println("numbers elements after retainAll operation is " + numbers); } }
Output of above program is shown below:
Elements of numbers list [10, 20, 30] Elements of numbers list [10, 15, 20, 30] Size of numbers list is 4 Element in numbers at 1st position is 15 numbers list contain element 20 ?: true Index of 15 in numbers list is 2 numbers list after appending odd numbers list [10, 15, 20, 30, 5, 25, 9] odd number list [] numbers list [10, 40, 20, 30, 5, 25, 9] numbers list after removing 40 [10, 20, 30, 5, 25, 9] element 5 removed ? true numbers contains [10, 20, 30, 25, 9] numbers elements after removeAll call [10, 20, 30] numbers elements after retainAll operation is [25, 9]
Java ArrayList removeIf
ArrayList removeIf method was added in Java 8. This method will remove all of the elements in the list which will satisfy the given prediacte. Below is the program of ArrayList removeIf example.
package com.walking.techie; import java.util.ArrayList; import java.util.List; import java.util.function.Predicate; public class ArrayListRemoveIfDemo { public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); // add numbers from 1 to 10 in ArrayList for (int i = 1; i <= 10; i++) { numbers.add(i); } Predicate<Integer> filter = new ArrayListRemoveIfDemo().new EvenPredicate<Integer>(); //ArrayList before removeIf operation System.out.println("Numbers list " + numbers); numbers.removeIf(filter); System.out.println("Numbers list after removeIf call " + numbers); } private class EvenPredicate<T> implements Predicate<Integer> { @Override public boolean test(Integer t) { return t%2==0; } } }
Output of above program is shown below:
Numbers list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Numbers list after removeIf call [1, 3, 5, 7, 9]
Java ArrayList replaceAll
ArrayList replaceAll method was added in Java 8. This method is useful when you want to apply some function on all the elements of the list. Below is the program of ArrayList replaceAll example.
package com.walking.techie; import java.util.ArrayList; import java.util.List; import java.util.function.UnaryOperator; public class ArrayListReplaceAllDemo { public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); // add numbers from 1 to 10 in ArrayList for (int i = 1; i <= 10; i++) { numbers.add(i); } // multiply all element by 2 UnaryOperator<Integer> operator = new ArrayListReplaceAllDemo().new EvenUnaryOperator<Integer>(); // ArrayList before replaceAll operation System.out.println("Numbers list " + numbers); numbers.replaceAll(operator); System.out.println("Numbers list after replaceAll call " + numbers); } private class EvenUnaryOperator<T> implements UnaryOperator<Integer> { @Override public Integer apply(Integer t) { return t * 2; } } }
Output of above program is shown below:
Numbers list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Numbers list after replaceAll call [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]
Java ArrayList subList
This method return portion of the list between the specified indexes from original list. The returned list is backed by original list, so non-structural changes in the returned list are reflected in this list, and vice-versa. The returned list supports all of the optional list operations. The semantics of the list returned by this method become undefined if the backing list (i.e., original list) is structurally modified in any way other than via the returned list. The structurally modification of original list change the actual modCount, when we try to work on sub list it will throw a ConcurrentModificationException.
Below is the program of ArrayList subList example.
package com.walking.techie; import java.util.ArrayList; import java.util.List; public class ArrayListSubListDemo { public static void main(String[] args) { List<Integer> numbers = new ArrayList<Integer>(); // add numbers from 1 to 10 in ArrayList for (int i = 1; i <= 10; i++) { numbers.add(i); } System.out.println("Original numbers array list " + numbers); //sublist between index 4 to 8 List<Integer> subList = numbers.subList(4, 8); System.out.println("sub list from numbers list "+ subList); //add 11 to subList, it will not change modCount subList.add(11); System.out.println("Original numbers array list after adding 11 to subList "+numbers); System.out.println("sub list after adding 11 to subList "+ subList); //Replaces the element at the 1th position in subList list with the 20. subList.set(1, 20); System.out.println("numbers list after set operation "+numbers); System.out.println("sub list after set operation " +subList); //add 11 to numbers list, it will change modCount numbers.add(12); System.out.println("numbers list after add operation " + numbers); //this line is fine System.out.println("sublist after adding 12 in numbers list " +subList); //this line will throw ConcurrentModificationException } }
Output of above program is shown below:
Original numbers array list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sub list from numbers list [5, 6, 7, 8]
Original numbers array list after adding 11 to subList [1, 2, 3, 4, 5, 6, 7, 8, 11, 9, 10]
sub list after adding 11 to subList [5, 6, 7, 8, 11]
numbers list after set operation [1, 2, 3, 4, 5, 20, 7, 8, 11, 9, 10]
sub list after set operation [5, 20, 7, 8, 11]
numbers list after add operation [1, 2, 3, 4, 5, 20, 7, 8, 11, 9, 10, 12]
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$SubList.checkForComodification(ArrayList.java:1231)
at java.util.ArrayList$SubList.listIterator(ArrayList.java:1091)
at java.util.AbstractList.listIterator(AbstractList.java:299)
at java.util.ArrayList$SubList.iterator(ArrayList.java:1087)
at java.util.AbstractCollection.toString(AbstractCollection.java:454)
at java.lang.String.valueOf(String.java:2994)
at java.lang.StringBuilder.append(StringBuilder.java:131)
at com.walking.techie.ArrayListSubListDemo.main(ArrayListSubListDemo.java:31)
Java ArrayList sort
We can use ArrayList sort method for sorting it's elements. Below is the program of ArrayList sort example. You can see in details about sort method in Comparable and Comparator topic.
package com.walking.techie; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class ArrayListSortDemo { public static void main(String[] args) { List<Integer> numbers=new ArrayList<Integer>(); numbers.add(23); numbers.add(34); numbers.add(13); numbers.add(2); numbers.add(28); System.out.println("Original numbers list before sorting "+ numbers); MyComparator<Integer> comp=new ArrayListSortDemo().new MyComparator<Integer>(); numbers.sort(comp); System.out.println("numbers list after sorting "+ numbers); } class MyComparator<T> implements Comparator<Integer>{ @Override public int compare(Integer o1, Integer o2) { return (o1 - o2); } } }
Output of above program is shown below:
Original numbers list before sorting [23, 34, 13, 2, 28] numbers list after sorting [2, 13, 23, 28, 34]
No comments :
Post a Comment