Java List Interface Explained With Example

The list in Java

The List is an interface of the Collection or you can say it extends the Collection. A List is an ordered collection of the elements with integer-based index.

A few main points about List Java interface are:

  • Elements can be added, removed and searched in the Java list, whereas you can add elements at the specified positions.
  • The index for list elements, just like arrays, starts from 0 (which is an integer).
  • The list may contain duplicate elements.
A List example

How to use list interface?

In order to use the List interface in your projects you must import the Java List as follows:

Import java.util.*;

How to make a list

After importing the java.util.* package, it is time to declare an object to create a new List.

List list_name = new ArrayList();

Or

List list_name = new LinkedList();

As such, the List is an interface, you cannot initialize a List object. The List is implemented in various classes like ArrayList, LinkedList, Vector, and Stack.

Example of creating and printing List elements

The following example shows how to create a new List object. It adds five elements and then a for loop is used to display the List elements.

Java List Interface

Experience this online



The output will be:

10

20

30

40

50

You can also use methods of the List interface to add, remove, search the elements in a List.

A few common methods of Java List are:

  • public void add(int index,Object element);
  • public object remove(int index);
  • public object get(int Index position);
  • public object set(int index,Object element);

Read Further: Java collection | Java ArrayList | Java Vector


Was this article helpful?

Related Articles

Leave A Comment?