Does ArrayList add to front or back?
In this Tutorial, we will Discuss Java ArrayList Methods such as add, addAll, remove, removeAll, size, contains, retainAll, Sort, Reverse, etc. with Examples: Show
In the previous tutorial, we explored the ArrayList data structure, and the ArrayList class provided for this data structure/collection in Java. We have learned creation, initialization, etc. of the ArrayList objects. Apart from these features that help us to define ArrayList, the ArrayList class in Java also provides a full-fledged function API that consists of methods that are used to manipulate ArrayList objects. => Check ALL Java Tutorials Here. These methods allow us to add, delete, search elements in the ArrayList as well as to retrieve the length/size of ArrayList elements, etc. In this tutorial, we will discuss these methods in detail with simple programming examples. What You Will Learn:
ArrayList Methods In JavaThe following table lists all the methods that are provided by the ArrayList class.
Next, we will discuss each of these methods from the ArrayList function API in detail and present programming examples. After discussing all the methods listed above, we will also take up some specific operations that are carried out using ArrayLists which are not a part of the ArrayList function API. ArrayList addI Prototype: boolean add (E e) II. Prototype: void add (int index, E element) Parameters: index=> Position at which the element is to be added. Return Value: void Description: Adds given element element at the specified position index by shifting the element at that position and subsequent elements to the right. Exceptions: IndexOutOfBoundsException => If the specified index is out of the range. ArrayList addAllI Prototype: boolean addAll (Collection c) Description: Adds all the elements in the given collection c to the end of the list. The result of the operation is undefined if the collection is altered when the operation is in progress. Exceptions: NullPointerException => If given collection c is null. II Prototype: boolean addAll (int index, Collection c) Description: Adds all the elements in the given collection c at the position specified by the index in the list. The element at the specified index and subsequent elements are shifted to the right. The result of the operation is undefined if the collection being added is altered when the operation is in progress. Exceptions: IndexOutOfBoundsException: if the index where the collection is to be added is out of bounds The following Java program demonstrates the usage of add and addAll methods. import java.util.*; class Main{ public static void main(String args[]){ //create an ArrayList ArrayListOutput: Initial ArrayList:[Delhi, Mumbai, Chennai, Kolkata] The above program uses both the versions of the add method to add elements to the list. It also adds a collection to the list at the specified index. Note the shifting of elements to the right of the ArrayList as evident from the output of the program. ArrayList Add To The FrontAs already mentioned, the first version of the add method adds the elements to the end of the list. If you want to add the elements at the beginning of the ArrayList, then you have to make use of the second version of the add method. This add method takes an index as a parameter. This index is the position at which the element is to be added. Thus to add the element at the beginning of the list, you have to specify the index as 0 which is the start of the list. The following program adds an element to the front of the ArrayList. import java.util.ArrayList; public class Main { public static void main(String[] args) { //define new ArrayList and initialize it ArrayListOutput: Initial ArrayList: ArrayList removeI. Prototype: E remove (int index) II. Prototype: boolean remove (Object o) Description: Deletes the first occurrence of element o from the list. If the element is not present in the list, then there is no effect of this operation. Once the element is deleted, the subsequent elements are shifted to the left. ArrayList removeAllPrototype: boolean removeAll (Collection c) Description: Removes all the elements from the list that match the elements in the given collection c. As a result, the elements remaining are shifted to the left of the list. Exceptions: ClassCastException => Class is not the same as that of the specified collection which implies class is incompatible. ArrayList removeRangePrototype: protected void removeRange (int fromIndex, int toIndex) Let us implement a Java program to demonstrate some of these remove methods that we discussed above. import java.util.*; class Main{ public static void main(String args[]){ //create an ArrayList ArrayListOutput: Initial ArrayList:[Delhi, Mumbai, Chennai, Kolkata, Pune, Hyderabad ArrayList size (Length)Prototype: int size () EnsureCapacity Prototype: void ensureCapacity (int minCapacity) trimToSize Prototype: void trimToSize() The below programming example demonstrates the methods size (), ensureCapacity () and trimToSize (). import java.util.ArrayList; public class Main { public static void main(String [] args) { //Create and initialize Arraylist ArrayListOutput: Initial size: 0 ArrayList containsPrototype: boolean contains (Object o) We make use of the contains method in the following program. import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize colorsList ArrayListOutput: ArrayList contains (Red Green): false As shown in the above output, the contains method checks if the argument provided is present in the ArrayList and returns true or false. ArrayList getPrototype: E get (int index) ArrayList set (Replace element)Prototype: E set (int index, E element) The Java program below uses get () and set () method to retrieve and replace values in the ArrayList. import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize colorsList ArrayListOutput: Entry at index 2 before call to set: Blue ArrayList clearPrototype: void clear () ArrayList isEmptyPrototype: boolean isEmpty () Clear () and isEmpty () functions are demonstrated below. import java.util.ArrayList; public class Main { public static void main(String[] args) { //create and initialize colorsList ArrayListOutput: The ArrayList: [Red, Green, Blue, White] ArrayList indexOfPrototype: int indexOf (Object o) ArrayList lastIndexOfPrototype: int lastIndexOf (Object o) The below Java program demonstrates the indexOf and lastIndexOf methods of ArrayList. Output: The ArrayList: [1, 1, 2, 3, 5, 3, 2, 1, 1] ArrayList toArrayPrototype: Object [] toArray () Prototype: Parameters: a=> Array to store elements of the list. If the size of the array is not enough for list elements, another array with the same type as a is created for storing elements. Return Value: T[] => Array that contains all the list elements. Exceptions: ArrayStoreException => If there is a mismatch in runtime type of the array and runtime type or supertype of its elements. The Java program below demonstrates the toArray method of ArrayList. import java.util.*; public class Main { public static void main(String[] args) { // define and initialize ArrayList ArrayListOutput: ArrayList: [10, 20, 30, 40, 50] ArrayList clonePrototype: Object clone () Output: Original ArrayList: [Apple, Orange, Melon, Grapes] From the above program output, you can see that the cloned ArrayList is a shallow copy of the original ArrayList. This means that when the original ArrayList is changed, these changes do not reflect in the cloned ArrayList as they do not share the memory locations of each element. For making a deep copy of Array, the original ArrayList needs to be traversed and each of its elements needs to be copied to the destination ArrayList. ArrayList subListPrototype: List Description: Returns a subList between a given range, fromIndex to index for the given list. Note that this sublist or the view of the list in the given range supports all the operations supported by the list. No view is returned if fromIndex = toIndex. Exceptions: IndexOutOfBoundsException => Thrown when toIndex is out of range. Let us see an example of the subList method. import java.util.ArrayList; import java.util.List; class Main{ public static void main(String a[]){ //create and initialize the ArrayList ArrayListOutput: Original ArrayList: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50] ArrayList retainAllPrototype: boolean retainAll (Collection c) Exceptions: ClassCastException => The collection type and list type do not match The following program demonstrates the retainAll method. import java.util.*; class Main{ public static void main(String args[]){ //create and initialize ArrayList ArrayListOutput: Original ArrayList:[Red, Green, Blue, Yellow] ArrayList IteratorPrototype: Iterator ArrayList listIteratorI. Prototype: ListIterator II. Prototype: ListIterator Example of iterator () and listIterator () methods. import java.util.*; class Main{ public static void main(String args[]){ //create ArrayList and initialize it ArrayListOutput: List contents using Iterator () method: Add Array To ArrayList In JavaArrayList supports the addAll method to add elements of the collection to the ArrayList. In a similar manner, you can also add an Array to the ArrayList. This is done using the Collections.addAll method. Example of adding an Array to the ArrayList. import java.util.*; class Main{ public static void main(String args[]){ //create an ArrayList ArrayListOutput: Initial ArrayList :[Delhi, Mumbai, Chennai, Kolkata] Sort ArrayList In JavaArrayList uses the Collections.sort method to sort its elements. By default, the list is sorted in ascending order by the Collections.sort method. If the ArrayList is to be sorted in descending order, then you have to provide Collections.reverseOrder() a parameter to the sort method. Given below is a program to sort an ArrayList in ascending and descending order: import java.util.*; public class Main { public static void main(String args[]){ //Create and initialize an ArrayList ArrayListOutput: Initial ArrayList:[Red, Green, Blue, Yellow] In case the ArrayList contains other class objects as elements, then you can make use of Comparable and Comparator interfaces. More details about interfaces will be covered in our later tutorials. Reverse An ArrayList In JavaYou can also reverse an ArrayList in Java. One method to do this is to use the traditional method of traversing the ArrayList in the reverse order and copy each element to a new ArrayList. Another method is using the Collections class which provides the reverse method that is used to reverse a collection. The program to reverse an ArrayList using the Collections class is given below. import java.io.*; import java.util.*; public class Main { public static void main(String[] args) { // create and initialize an ArrayList ArrayListOutput: Initial ArrayList: [1, 3, 5, 7, 9] Remove Duplicates From An ArrayList In JavaTo remove duplicates from the ArrayList, you can once again resort to the traditional method of using an iterator to traverse through the ArrayList and store only the first occurrence of the element into a different ArrayList. Yet another method is by using the distinct () method of stream () class. This method returns a stream of distinct elements. The stream () feature is available in Java from Java 8 onwards. The implementation of stream ().distinct () method is given below: import java.util.*; import java.util.stream.Collectors; public class Main { public static void main(String[] args) { // Create an ArrayList of numbers ArrayListOutput: Original ArrayList:[1, 2, 3, 1, 3, 5, 5, 6, 6, 7, 7, 8, 8] Shuffle (Randomize) An ArrayList In JavaYou can also shuffle or randomize the ArrayList elements. This is done using the Collections.shuffle () method. Using this method, either you can shuffle the ArrayList with default settings or provide a random () function that will randomize the elements according to the random value provided. A Java program to achieve this is given below. import java.util.*; public class Main { public static void main(String[] args) { //create and initialize a String ArrayList ArrayListOutput: Original ArrayList :[east, west, north, south, southwest, northeast] Shuffled ArrayList without Random() :[north, northeast, east, southwest, south, west] Frequently Asked QuestionsQ #1) What is the difference between Homogeneous and Heterogeneous containers in Java? Answer: Homogeneous containers contain objects/elements of the same type. On the other hand, heterogeneous containers have objects of mixed type. Q #2) Is ArrayList in Java Heterogeneous? Answer: Yes. Since ArrayLists support generics and therefore type erasure, it can contain mixed objects when implemented as a generic ArrayList. Q #3) Can ArrayList store int? Answer: No. ArrayLists cannot store values like int but it can store Integer objects as ArrayLists can contain only objects. Thus to store primitive types you should use wrapper classes like Integer for ints. Q #4) What happens when ArrayList is full? Answer: Every ArrayList object has a feature named capacity. When the ArrayList is full, the capacity of the ArrayList increases automatically to make room for more elements. Q #5) What is the difference between the removeAll and retainAll method in ArrayList? Answer: The ArrayList methods removeAll and retainAll exhibit opposite behavior. While the removeAll method removes all the elements from the list that match with the collection passed as an argument to this method, retainAll, on the other hand, retains all the elements in the list that match with that of the collection. ConclusionIn this tutorial, we have discussed ArrayList methods in detail with an example. We have also considered some special cases like adding elements to the front of the list. We also discussed other operations on ArrayList like sorting, reversing, and shuffling of ArrayList. In our upcoming tutorial, we will discuss some of the ArrayList conversions. => Watch Out The Simple Java Training Series Here. Recommended Reading
|