Java List Interface

tutorial and example
tutorial and example

JAVA LIST INTERFACE

List interface : List interface is used when we have to order a collection which contains duplicate entries. Like an array, the elements of its implementation classes are retrieved and inserted at specific position. The main thing about the list implementations is that they are ordered and allow duplicates.

  • ArrayList : ArrayList are like auto resizable array. When we add elements, the size of the array grows automatically. The main benefit of an arrayList is that we can lookup any element in a constant time. ArrayList is a good choice when read operation  occurs more often than (or the same amounts) write operation in the ArrayList.
  • LinkedList : A LinkedList implements both List and Queue Interface. It has all of the methods of a List. It also has methods which can be used to add or remove elements from the beginning and end of a list. The main benefit of the LinkedList is that at constant time, we can access, add and remove elements from the beginning and end of the list. It is suitable when we want functionality like a queue.

Useful methods

Return Type

Method

Description

void

add(E element)

It adds element to end.

void

add(int index, E element)

It adds element at index and moves the rest toward the end.

E

get(int index)

It returns element at index.

int

indexOf(Object o)

It returns first matching index or -1 if not found.

int

lastIndexOf(Object o)

It returns last matching index or -1 if not found.

void

remove(int index)

It removes element at index and moves the rest towards the front.

E

set(int index, E e)

It replaces element at index and returns original.

Example:

Output: