how to use arraylist in java

The java.util.ArrayList class is one of the most commonly used classes in the Collection Framework. Array List is an implementation that stores elements in a backing array. The array’s size will be automatically expanded if there isn’t enough room when adding new elements to the list.

Therefore, ArrayList methods can be considered if we want fast, random access to the elements. It’s like an array of vitamins.

Some of the advantages ArrayList has over arrays are:

  • ArrayList can grow dynamically
  • It provides more powerful insertion and search mechanisms than arrays
  • ArrayList contains duplicate elements
  • It maintains insertion order
  • ArrayList is unsynchronized
  • It allows random access because array works on the index basis
  • In this, manipulation is slow because a lot of shifting needs to occur if any element is removed from the array list


Methods of ArrayList class

  •  add( Object o): This method adds an object o to the ArrayList.

  • add(int index, Object o): It adds the object o to the array list at the given index.

  • remove(Object o): Removes the object o from the ArrayList.

  • remove(int index): Removes an element from a given index.

  •  set(int index, Object o): Used for updating an element. It replaces the element present at the specified index with the object o.

  •  int indexOf(Object o): Gives the index of the object o. If the element is not found in the list then returns the value -1.

  • Object get(int index): It returns the object of a list which is present at the specified index.

  •  int size(): It gives the size of the ArrayList – Number of elements of the list.

  • boolean contains(Object o): It checks whether the given object o is present in the array list if its there then returns true else returns false.

  • clear(): It is used for removing all the elements of the array list in one go. The below code will remove all the elements of ArrayList whose object is obj.

Java Array List Example

Find The Working Example Of ArrayLists on codedbug GitHub Repo.

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?