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:

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 Java
    • ArrayList add
    • ArrayList addAll
    • ArrayList Add To The Front
    • ArrayList remove
    • ArrayList removeAll
    • ArrayList removeRange
    • ArrayList size [Length]
    • ArrayList contains
    • ArrayList get
    • ArrayList set [Replace element]
    • ArrayList clear
    • ArrayList isEmpty
    • ArrayList indexOf
    • ArrayList lastIndexOf
    • ArrayList toArray
    • ArrayList clone
    • ArrayList subList
    • ArrayList retainAll
    • ArrayList Iterator
    • ArrayList listIterator
    • Add Array To ArrayList In Java
    • Sort ArrayList In Java
    • Reverse An ArrayList In Java
    • Remove Duplicates From An ArrayList In Java
    • Shuffle [Randomize] An ArrayList In Java
    • Frequently Asked Questions
  • Conclusion
    • Recommended Reading

ArrayList Methods In Java

The following table lists all the methods that are provided by the ArrayList class.

MethodMethod PrototypeMethod Description
Addboolean add[E e]Adds given element e to the end of the list.
void add[int index, E element]Adds given element element at the specified position index.
AddAllboolean addAll [Collection extends E> c]Adds all the elements in the given collection c to the end of the list.
boolean addAll [int index, Collection extends E> c]Adds all the elements in the given collection c at the position specified by the index in the list.
Clearvoid clear[]Clears the list by removing all the elements from the list.
CloneObject clone[]Makes a shallow copy of the given ArrayList.
Containsboolean contains[Object o]Checks if the list contains the given element o. Returns true if the element is present.
ensureCapacityvoid ensureCapacity [int minCapacity]Increases the capacity of the ArrayList to ensure it has the minCapacity.
GetE get[int index]Returns the element in the list present at the position specified by index.
indexOfint indexOf[Object o]Returns the index of the first occurrence of element o in the list. -1 if element o is not present in the list.
isEmptyboolean isEmpty[]Checks if the given list is empty.
IteratorIterator iterator[]Returns an iterator to traverse over the list elements in the proper sequence.
lastIndexOfint lastIndexOf[Object o]Returns the index of the last occurrence of the specified element o in the list. -1 if the element is not present in the list.
listIteratorListIterator listIterator[]Returns list iterator to traverse over the elements of the given list.
ListIterator listIterator[int index]Returns the list iterator starting from the specified position index to traverse over the elements of the given list.
removeE remove[int index]Deletes element at the index in the ArrayList.
boolean remove[Object o]Deletes the first occurrence of element o from the list.
removeAllboolean removeAll[Collection c]Removes all the elements from the list that match the elements in given collection c.
removeRangeprotected void removeRange [int fromIndex, int toIndex]Removes elements specified in the given range, fromIndex [inclusive] to toIndex [exclusive] from the list.
retainAllboolean retainAll[Collection c]Retains those elements in the list that match the elements in the given collection c.
setE set[int index, E element]Sets the element value at given index to the new value given by element.
sizeint size[]Returns the total number of elements or length of the list.
subListList subList[int fromIndex, int toIndex]Returns a subList between given range, fromIndex to toIndex for the given list.
toArrayObject[] toArray[]Converts the given list into an array.
T[] toArray[T[] a]Converts the given list into an array of the type given by a.
trimToSizevoid trimToSize[]Trims the ArrayList capacity to the size or number of elements present in the list.

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 add

I

Prototype: boolean add [E e]
Parameters: e=> Element to be added to the ArrayList.
Return Value: true=> Element successfully added.
Description: Adds the given element e to the end of the list.

II.

Prototype: void add [int index, E element]

Parameters:

index=> Position at which the element is to be added.
Element=> Element to be added to the ArrayList.

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 addAll

I

Prototype: boolean addAll [Collection c]
Parameters: c=> Collection whose elements match with those of ArrayList and are to be removed.
Return Value: true=> If the ArrayList is altered by the operation.

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.
NullPointerException => If the given collection c is null; or if c has a null element and it is not allowed by the collection.

ArrayList removeRange

Prototype: protected void removeRange [int fromIndex, int toIndex]
Parameters: fromIndex=> Index of the starting element of the range to be removed.
toIndex=> Index of the element after the last element in the range to be removed.
Return Value: void
Description: Removes elements specified in the given range, fromIndex [inclusive] to toIndex [exclusive] from the list. This operation shortens the length of the list by [toIndex-fromIndex]. This operation has no effect in case fromIndex = toIndex.
Exceptions: IndexOutOfBoundsException=> If any of the indices [fromIndex or toIndex] is out of bounds.

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 ArrayList city_List=new ArrayList[Arrays.asList["Delhi","Mumbai","Chennai", "Kolkata", "Pune", "Hyderabad"]]; //print the list System.out.println["Initial ArrayList:" + city_List]; //remove element at index 2 city_List.remove[2]; //print the list System.out.println["\nArrayList after removing element at index 2:" + city_List]; //remove the element "Kolkata" city_List.remove["Kolkata"]; //print the list System.out.println["\nArrayList after removing element -> Kolkata:" + city_List]; //create new list ArrayList newCities=new ArrayList[Arrays.asList["Delhi","Hyderabad"]]; //call removeAll to remove elements contained in newCities list. city_List.removeAll[newCities]; //print the list System.out.println["\nArrayList after call to removeAll:" + city_List]; } }

Output:

Initial ArrayList:[Delhi, Mumbai, Chennai, Kolkata, Pune, Hyderabad
ArrayList after removing element at index 2:[Delhi, Mumbai, Kolkata, Pune, Hyderabad]
ArrayList after removing element -> Kolkata:[Delhi, Mumbai, Pune, Hyderabad]
ArrayList after call to removeAll:[Mumbai, Pune]

ArrayList size [Length]

Prototype: int size []
Parameters: NIL
Return Value: int=> Number of elements in the ArrayList.
Description: Returns the total number of elements or the length of the ArrayList.

EnsureCapacity

Prototype: void ensureCapacity [int minCapacity]
Parameters: minCapacity=> The minimum capacity desired for the ArrayList.
Return Value: void
Description: Increases the capacity of the ArrayList to ensure that it has the minCapacity.

trimToSize

Prototype: void trimToSize[]
Parameters: NIL
Return Value: void
Description: Trims the ArrayList capacity to the size or number of elements present in the list.

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 ArrayList evenList=new ArrayList[5]; System.out.println["Initial size: "+evenList.size[]]; evenList.add[2]; evenList.add[4]; evenList.add[6]; evenList.add[8]; evenList.add[10]; //print the list and size System.out.println["Original List: " + evenList]; System.out.println["ArrayList Size after add operation: "+evenList.size[]]; //call ensureCapacity [] with minimum capacity =10 evenList.ensureCapacity[10]; //add two more elements evenList.add[12]; evenList.add[14]; //print the size again System.out.println["ArrayList Size after ensureCapacity[] call and add operation: "+evenList.size[]]; //call trimToSize[] evenList.trimToSize[]; //print the size and the ArrayList System.out.println["ArrayList Size after trimToSize[] operation: "+evenList.size[]]; System.out.println["ArrayList final: "]; for[int num: evenList]{ System.out.print[num + " "]; } } }

Output:

Initial size: 0
Original List: [2, 4, 6, 8, 10]
ArrayList Size after add operation: 5
ArrayList Size after ensureCapacity[] call and add operation: 7
ArrayList Size after trimToSize[] operation: 7
ArrayList final:
2 4 6 8 10 12 14

ArrayList contains

Prototype: boolean contains [Object o]
Parameters: o=> Element which is to be checked if present in the ArrayList.
Return Value: true=> If the ArrayList contains element o.
Description: Checks if the list contains the given element o. Returns true if the element is present.

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 ArrayList colorsList = new ArrayList[]; colorsList.add["Red"]; colorsList.add["Green"]; colorsList.add["Blue"]; colorsList.add["White"]; //call contains method to check if different strings are present in ArrayList System.out.println["ArrayList contains ['Red Green']: " +colorsList.contains["Red Green"]]; System.out.println["ArrayList contains ['Blue']: " +colorsList.contains["Blue"]]; System.out.println["ArrayList contains ['Yellow']: " +colorsList.contains["Yellow"]]; System.out.println["ArrayList contains ['White']: " +colorsList.contains["White"]]; } }

Output:

ArrayList contains [Red Green]: false
ArrayList contains [Blue]: true
ArrayList contains [Yellow]: false
ArrayList contains [White]: true

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 get

Prototype: E get [int index]
Parameters: index=> Index at which element is to be retrieved from the ArrayList.
Return Value: E=> Element value at the given index in the ArrayList.
Description: Returns the element in the list present at the position specified by index.
Exceptions: IndexOutOfBoundsException => If index is out of bounds.

ArrayList set [Replace element]

Prototype: E set [int index, E element]
Parameters: index=> Index at which the element is to be replaced.
Element=> New element to be set at the index specified.
Return Value: E => Element that is replaced by the set operation.
Description: Sets the element value at the given index to the new value given by element.
Exceptions: IndexOutOfBoundsException => If index is out of bounds

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 ArrayList colorsList = new ArrayList[]; colorsList.add["Red"]; colorsList.add["Green"]; colorsList.add["Blue"]; colorsList.add["White"]; //call get [] method to retrieve value at index 2 System.out.println["Entry at index 2 before call to set: " + colorsList.get[2]]; //replace the value at index 2 with new value colorsList.set[2,"Yellow"]; //print the value at index 2 again System.out.println["Entry at index 2 after call to set: " + colorsList.get[2]]; } }

Output:

Entry at index 2 before call to set: Blue
Entry at index 2 after call to set: Yellow

ArrayList clear

Prototype: void clear []
Parameters: NIL
Return Value: void
Description: Clears the list by removing all the elements from the list.

ArrayList isEmpty

Prototype: boolean isEmpty []
Parameters: NIL
Return Value: true=> if list is empty
Description: Checks if the given list is empty.

Clear [] and isEmpty [] functions are demonstrated below.

import java.util.ArrayList; public class Main { public static void main[String[] args] { //create and initialize colorsList ArrayList colorsList = new ArrayList[]; colorsList.add["Red"]; colorsList.add["Green"]; colorsList.add["Blue"]; colorsList.add["White"]; //print the ArrayList System.out.println["The ArrayList: " + colorsList]; //call clear[] nethod on ArrayList colorsList.clear[]; //check if ArrayList is empty using isEmpty[] method System.out.println["Is ArrayList empty after clear []? :" + colorsList.isEmpty[]]; } }

Output:

The ArrayList: [Red, Green, Blue, White]
Is ArrayList empty after clear []? :true

ArrayList indexOf

Prototype: int indexOf [Object o]
Parameters: o=> Element whose index is to be found in the ArrayList.
Return Value: int => Index of the first occurrence of the element in the list.
Description: Returns the index of the first occurrence of the element o in the list. -1 if the element o is not present in the list.

ArrayList lastIndexOf

Prototype: int lastIndexOf [Object o]
Parameters: o=> The element to be searched for.
Return Value: int=> Index of the last occurrence of the element in the list.
Description: Returns the index of the last occurrence of the specified element o in the list. -1 if the element is not present in the list.

The below Java program demonstrates the indexOf and lastIndexOf methods of ArrayList.

import java.util.ArrayList; public class Main { public static void main[String[] args] { //create and initialize intList ArrayList intList = new ArrayList[]; intList.add[1]; intList.add[1]; intList.add[2]; intList.add[3]; intList.add[5]; intList.add[3]; intList.add[2]; intList.add[1]; intList.add[1]; //print the ArrayList System.out.println["The ArrayList: " + intList]; //call indexOf[] and lastIndexOf[] methods to check the indices of specified elements System.out.println["indexOf[1] : " + intList.indexOf[1]]; System.out.println["lastIndexOf[1] : " + intList.lastIndexOf[1]]; System.out.println["indexOf[2] : " + intList.indexOf[2]]; System.out.println["lastIndexOf[2] : " + intList.lastIndexOf[2]]; System.out.println["indexOf[3] : " + intList.indexOf[3]]; System.out.println["lastIndexOf[3] : " + intList.lastIndexOf[3]]; System.out.println["indexOf[5] : " + intList.indexOf[5]]; System.out.println["lastIndexOf[5] : " + intList.lastIndexOf[5]]; } }

Output:

The ArrayList: [1, 1, 2, 3, 5, 3, 2, 1, 1]
indexOf[1] : 0
lastIndexOf[1] : 8
indexOf[2] : 2
lastIndexOf[2] : 6
indexOf[3] : 3
lastIndexOf[3] : 5
indexOf[5] : 4
lastIndexOf[5] : 4

ArrayList toArray

Prototype: Object [] toArray []
Parameters: NIL
Return Value: Object [] =>an array. This returned array contains all the elements of the list in a proper sequence.
Description: Converts the given list into an array.

Prototype: T[] toArray [T[] a]

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.
Description: Converts the given list into an array of the type given by a.

Exceptions: ArrayStoreException => If there is a mismatch in runtime type of the array and runtime type or supertype of its elements.
NullPointerException => The given array is null

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 ArrayList intList = new ArrayList[]; intList.add[10]; intList.add[20]; intList.add[30]; intList.add[40]; intList.add[50]; // print ArrayList System.out.println["ArrayList: " + intList]; //declare array Integer myArray[] = new Integer[intList.size[]]; //use toArray method to convert ArrayList to Array myArray = intList.toArray[myArray]; //print the Array System.out.println["Array from ArrayList:" + Arrays.toString[myArray]]; } }

Output:

ArrayList: [10, 20, 30, 40, 50]
Array from ArrayList:[10, 20, 30, 40, 50]

ArrayList clone

Prototype: Object clone []
Parameters: NIL
Return Value: Object=> Clone of the ArrayList instance.
Description: Makes a shallow copy of the given ArrayList.

import java.util.ArrayList; public class Main { public static void main[String a[]]{ ArrayList fruitsList = new ArrayList[]; //Adding elements to the ArrayList fruitsList.add["Apple"]; fruitsList.add["Orange"]; fruitsList.add["Melon"]; fruitsList.add["Grapes"]; System.out.println["Original ArrayList: "+fruitsList]; ArrayList clone_list = [ArrayList]fruitsList.clone[]; System.out.println["Cloned ArrayList: "+ clone_list]; //add one elmeent & remove one element from original arraylist fruitsList.add["Mango"]; fruitsList.remove["Orange"]; //print original and cloned ArrayList again System.out.println["\nOriginal ArrayList after add & remove:"+fruitsList]; System.out.println["Cloned ArrayList after original changed:"+clone_list]; } }

Output:

Original ArrayList: [Apple, Orange, Melon, Grapes]
Cloned ArrayList: [Apple, Orange, Melon, Grapes]
Original ArrayList after add & remove:[Apple, Melon, Grapes, Mango]
Cloned ArrayList after original changed:[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 subList

Prototype: List subList [int fromIndex, int toIndex]
Parameters: fromIndex=> Starting index of the range [inclusive]
toIndex=> End index of the range [exclusive]
Return Value: List => Sublist of the list in the given range.

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.
IllegalArgumentException=> If fromIndex > toIndex i.e. indices are out of order.

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 ArrayList intList = new ArrayList[]; intList.add[5]; intList.add[10]; intList.add[15]; intList.add[20]; intList.add[25]; intList.add[30]; intList.add[35]; intList.add[40]; intList.add[45]; intList.add[50]; //print the ArrayList System.out.println["Original ArrayList: "+intList]; //create a sublist for the given ArrayList ArrayList sub_ArrayList = new ArrayList[intList.subList[2, 6]]; //print the sublist System.out.println["Sublist of given ArrayList: "+sub_ArrayList]; } }

Output:

Original ArrayList: [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Sublist of given ArrayList: [15, 20, 25, 30]

ArrayList retainAll

Prototype: boolean retainAll [Collection c]
Parameters: c=> Collection with elements that are to be retained in the list.
Return Value: true=> If the ArrayList changed as a result of the operation.
Description: Retains those elements in the list that match the elements in the given collection c.

Exceptions: ClassCastException => The collection type and list type do not match
NullPointerException => Given collection is null or the list contains null element and collection does not permit nulls.

The following program demonstrates the retainAll method.

import java.util.*; class Main{ public static void main[String args[]]{ //create and initialize ArrayList ArrayList colorsList=new ArrayList[]; colorsList.add["Red"]; colorsList.add["Green"]; colorsList.add["Blue"]; colorsList.add["Yellow"]; //print the ArrayList System.out.println["Original ArrayList:" + colorsList]; //define another collection ArrayList color_collection=new ArrayList[]; color_collection.add["Red"]; color_collection.add["Blue"]; System.out.println["Collection elements to be retained in the list:" + color_collection]; //call retainAll method with above collection as an argument colorsList.retainAll[color_collection]; //print the ArrayList after retainAll call. System.out.println["ArrayList after retainAll call:" + colorsList]; } }

Output:

Original ArrayList:[Red, Green, Blue, Yellow]
Collection elements to be retained in the list:[Red, Blue]
ArrayList after retainAll call:[Red, Blue]

ArrayList Iterator

Prototype: Iterator iterator []
Parameters: NIL
Return Value: Iterator => iterator over the list elements.
Description: Returns an iterator to traverse over the list elements in the proper sequence.

ArrayList listIterator

I.

Prototype: ListIterator listIterator []
Parameters: NIL
Return Value: ListIterator => listIterator over the list elements.
Description: Returns list iterator to traverse over the elements of the given list.

II.

Prototype: ListIterator listIterator [int index]
Parameters: index=> Position of the first element in the listIterator.
Return Value: ListIterator => ListIterator for the list from specified index.
Description: Returns the list iterator starting from the specified position index to traverse over the elements of the given list.
Exceptions: IndexOutOfBoundsException => Given index is out of range.

Example of iterator [] and listIterator [] methods.

import java.util.*; class Main{ public static void main[String args[]]{ //create ArrayList and initialize it ArrayList cities=new ArrayList[]; cities.add["Mumbai"]; cities.add["Pune"]; cities.add["Hyderabad"]; cities.add["Delhi"]; //use iterator[] method to traverse through the list System.out.println["List contents using Iterator [] method:"]; Iterator iter=cities.iterator[]; while[iter.hasNext[]]{ System.out.print[iter.next[] + " "]; } //use listIterator[] method to traverse through the list System.out.println["\n\nList contents using listIterator [] method:"]; ListIterator list_iter=cities.listIterator[]; while[list_iter.hasNext[]] { System.out.print[list_iter.next[] + " "]; } } }

Output:

List contents using Iterator [] method:
Mumbai Pune Hyderabad Delhi
List contents using listIterator [] method:
Mumbai Pune Hyderabad Delhi

Add Array To ArrayList In Java

ArrayList 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 ArrayList city_List=new ArrayList[]; //add elements to the ArrayList using add method city_List.add["Delhi"]; city_List.add["Mumbai"]; city_List.add["Chennai"]; city_List.add["Kolkata"]; //print ArrayList System.out.println["\nInitial ArrayList :" + city_List]; //define an array. String[] myArray = new String[]{"Cochin", "Goa"}; //add the array to the ArrayList Collections.addAll[city_List,myArray]; //print the ArrayList System.out.println["\nArrayList after adding array :" + city_List]; } }

Output:

Initial ArrayList :[Delhi, Mumbai, Chennai, Kolkata]
ArrayList after adding array :[Delhi, Mumbai, Chennai, Kolkata, Cochin, Goa]

Sort ArrayList In Java

ArrayList 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 ArrayList colorsList = new ArrayList[]; colorsList.add["Red"]; colorsList.add["Green"]; colorsList.add["Blue"]; colorsList.add["Yellow"]; //print initial ArrayList System.out.println["Initial ArrayList:" + colorsList]; //sort ArrayList in ascending order Collections.sort[colorsList]; //print sorted ArrayList System.out.println["\nArrayList sorted in ascending order:"]; System.out.println[colorsList]; //sort ArrayList in reverse[desending] order Collections.sort[colorsList, Collections.reverseOrder[]]; //print sorted list System.out.println["\nArrayList sorted in descending order:"]; System.out.println[colorsList]; } }

Output:

Initial ArrayList:[Red, Green, Blue, Yellow]
ArrayList sorted in ascending order:
[Blue, Green, Red, Yellow]
ArrayList sorted in descending order:
[Yellow, Red, Green, Blue]

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 Java

You 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 ArrayList oddList = new ArrayList[]; oddList.add[1]; oddList.add[3]; oddList.add[5]; oddList.add[7]; oddList.add[9]; System.out.print["Initial ArrayList: " + oddList]; // use Collections.reverse method to reverse the ArrayList Collections.reverse[oddList]; //print the ArrayList System.out.print["\nReversed ArrayList: " + oddList]; } }

Output:

Initial ArrayList: [1, 3, 5, 7, 9]
Reversed ArrayList: [9, 7, 5, 3, 1]

Remove Duplicates From An ArrayList In Java

To 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 ArrayList numList = new ArrayList [Arrays.asList[1, 2, 3, 1, 3, 5, 5, 6, 6, 7, 7, 8, 8]]; //print the original ArrayList System.out.println["Original ArrayList:" + numList]; //Use Java 8 stream[].distinct[] method to remove duplicates from the list List distinctList = numList.stream[].distinct[].collect[Collectors.toList[]]; //print the new list System.out.println["ArrayList without duplicates:" + distinctList]; } }

Output:

Original ArrayList:[1, 2, 3, 1, 3, 5, 5, 6, 6, 7, 7, 8, 8]
ArrayList without duplicates:[1, 2, 3, 5, 6, 7, 8]

Shuffle [Randomize] An ArrayList In Java

You 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 ArrayList strlist = new ArrayList[]; strlist.add["east"]; strlist.add["west"]; strlist.add["north"]; strlist.add["south"]; strlist.add["southwest"]; strlist.add["northeast"]; //print the original list System.out.println["Original ArrayList : \n" + strlist]; //shuffle the ArrayList without random function Collections.shuffle[strlist]; System.out.println["\nShuffled ArrayList without Random[] : \n" + strlist]; // shuffle the ArrayList with random[] function Collections.shuffle[strlist, new Random[]]; System.out.println["\nShuffled ArrayList with Random[] : \n" + strlist]; // use random [2] to shuffle the ArrayList Collections.shuffle[strlist, new Random[2]]; System.out.println["\nShuffled ArrayList with Random[2] : \n" + strlist]; } }

Output:

Original ArrayList :[east, west, north, south, southwest, northeast] Shuffled ArrayList without Random[] :[north, northeast, east, southwest, south, west]
Shuffled ArrayList with Random[] :[south, east, north, northeast, west, southwest]
Shuffled ArrayList with Random[2] :[southwest, south, east, northeast, north, west]

Frequently Asked Questions

Q #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.

Conclusion

In 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

  • Java ArrayList - How To Declare, Initialize & Print An ArrayList
  • Java ArrayList Conversions To Other Collections
  • Reverse An Array In Java - 3 Methods With Examples
  • Arrays In Java 8 - Stream Class And ParallelSort Method
  • How To Sort An Array In Java - Tutorial With Examples
  • Introduction To Java Arrays And Related Concepts
  • Jagged Array In Java - Tutorial With Examples
  • Java Array - Declare, Create & Initialize An Array In Java

Video liên quan

Chủ Đề