Java ArrayList

The ArrayList is a Collection class and a part of the java.util package i.e., import the java.util.ArrayList package. It implements the List interface. The size of an ArrayList can be modified i.e., you can easily add or remove elements. This is not the case with Arrays in Java. Once created, you cannot modify the Java Arrays. ArrayList can have duplicate elements.

Let us see some ArrayList methods/ operations with examples:

  • Create an ArrayList
  • Size of an ArrayList
  • Loop through the ArrayList
  • Sort an ArrayList
  • Access an ArrayList element
  • Remove an ArrayList element

Let us first see how to create an ArrayList in Java:

Create an ArrayList

To create an ArrayList, set the type in angular braces i.e., use the wrapper class. For example, for creating an ArrayList with string elements, use <String>:

Let us now see an example and create an ArrayList in Java with string elements:

Output

Size of an ArrayList

To get the size of an ArrayList i.e., how many elements it has, use the size() method. Let us see an example:

Output

Loop through the ArrayList

Use the for loop to loop through the ArrayList in Java. Let us see an example:

Output

Sort an ArrayList

To sort an ArrayList in Java, use the Collections.sort() method. Let us see an example:

Output

Access an ArrayList element

To access an element of an ArrayList, use the get() method. Set the index number of the element you want to access as a parameter of the get() method. For example, to access the 3rd element, set index 2 i.e.:

To access the 5th element, set index 4 i.e.:

Let us now see an example to access an element of an ArrayList in Java:

Output

Remove an ArrayList element

To remove an element from an ArrayList, use the remove() method. Set the index number of the element you want to remove as a parameter of the remove () method. For example, to remove the 3rd element, set index 2 i.e.:

To access the 5th element, set index 4 i.e.:

Let us now see an example of removing elements from an ArrayList in Java:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


Java LinkedList
Java HashSet
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading