ArrayList Flashcards
Difference between Collection and Collections
- A Collection is an interface, whereas Collections is a class.
- A Collection interface provides the standard functionality of a data structure to List, Set, and Queue. However, the Collections class provides the utility methods that can be used to search, sort, and synchronize collection elements.
ArrayList
is the most widely used implementation of the List interface.
Features:
- Elements are stored in the order of insertion.
- It allows the storage of duplicate elements.
- ArrayList also supports null elements.
- Resizable
- Java 8 utilizes “Lazy Initialzation” to save memory.
Three ways to create an ArrayList
- List list = new ArrayList(); -default constructor, size 0.
- List list = new ArrayList(50); - capacity included, no resize needed
- List list - new ArrayList(oldList); - using an existing collection
Four ways to add elements in an ArrayList
- add(E e) - inserting single element at the end
- add(int index, E element) - insert an element at a particular index & shift to the right
- adAlll(Collection c) - add all the elements at the end of the ArrayList.
- addAll(int index, Collection c) - add all elements at a particular index & shift to the right
How to make a ArrayList a Parameterized Type
List list = new ArrayList<>();
Creating a parameterized Collection is very important. Without it, there can be serious errors
Fetching an element in an ArrayList
list.get(int index);
Removing an element from an ArrayList
- remove(int index) -to remove an element at a particular index
- remove(Object o) - the first occurrence of that element will be removed.
- removeRange(int fromIndex, int toIndex) -will remove, from this list, all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive. ArrayList exclusive*
- removeAll(Collection> c) - to remove, from the given list, all of the elements that are contained in the specified collection.
- clear() - o remove all the elements from the ArrayList.
Replacing all the elements of the ArrayList
A new method, replaceAll(UnaryOperator operator), was added in Java 8. This method takes a single UnaryOperator type argument. The UnaryOperator interface is a functional interface that has a single abstract method, apply(), that returns a result of the same object type as the operand.
Updating an element in ArrayList
To update an element in ArrayList, the set(int index, E e) method can be used. This method takes the index, which needs to be updated and a new value.
Checking if an element is present in the ArrayList
- contains(Object o) method. This method returns true if the element is present in the list; otherwise, it returns false.
- indexOf(Object o) - If we need the index of the first occurrence of the element
- lastIndexOf(Object o) - if we need the last occurrence of the element