Java ArrayList class

Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class and implements List interface.

  1. Java ArrayList class can contain duplicate elements.
  2. Java ArrayList class maintains insertion order.
  3. Java ArrayList class is non synchronized.
  4. Java ArrayList allows random access because array works at the index basis.

ArrayList class declaration

public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable

Constructors of Java ArrayList

  1. ArrayList()

    It is used to build an empty array list.

  2. ArrayList(Collection c)

    It is used to build an array list that is initialized with the elements of the collection c.

  3. ArrayList(int capacity)

    It is used to build an array list that has the specified initial capacity.

Methods of Java ArrayList

  1. void add(int index, Object element)

    It is used to insert the specified element at the specified position index in a list.

  2. boolean addAll(Collection c)

    It is used to append all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator.

  3. void clear()

    It is used to remove all of the elements from this list.

  4. int lastIndexOf(Object o)

    It is used to return the index in this list of the last occurrence of the specified element, or -1 if the list does not contain this element.

  5. Object[] toArray()

    It is used to return an array containing all of the elements in this list in the correct order.

  6. Object[] toArray(Object[] a)

    It is used to return an array containing all of the elements in this list in the correct order.

  7. boolean add(Object o)

    It is used to append the specified element to the end of a list.

  8. boolean addAll(int index, Collection c)

    It is used to insert all of the elements in the specified collection into this list, starting at the specified position.

  9. Object clone()

    It is used to return a shallow copy of an ArrayList.

  10. int indexOf(Object o)

    It is used to return the index in this list of the first occurrence of the specified element, or -1 if the List does not contain this element.

Java Non-generic Vs Generic Collection

ArrayList al=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection. ArrayList al=new ArrayList();//creating new generic arraylist

EXAMPLE

Flash Soon


Two ways to iterate the elements of collection in java

There are two ways to traverse collection elements:

  • By Iterator interface.
  • EXAMPLE

    Flash Soon


  • User-defined class objects in Java ArrayList
  • >

    EXAMPLE

    Flash Soon



    Copyright ©2017 Design& develop