Skip to main content

Java List Interface

Introduction

In Java, the List Interface is a part of the Java Collections Framework. This is a sub-interface of the Collection interface, which provides methods to create and manipulate groups of objects. In this tutorial, we are going to explore the List Interface in detail.

What is a List?

A List in Java can be seen as a resizable array or an ordered collection that can contain duplicate elements. It also allows us to insert elements at any position in the list.

Declaration of a List

A List can be declared as follows:

List<String> list1 = new ArrayList<String>(); 
List<Integer> list2 = new LinkedList<Integer>();
List<String> list3 = new Vector<String>();
List<Integer> list4 = new Stack<Integer>();

In the above examples, we have declared different types of lists like ArrayList, LinkedList, Vector, and Stack. All of these classes implement the List interface.

Methods in List Interface

The List interface includes all the methods of the Collection interface. It also provides some methods that can be used specifically with a list. Let's discuss some of these methods:

1. void add(int index, Object element)

This method is used to insert an element at a specific position in the list.

List<String> list = new ArrayList<String>();
list.add(0, "Apple");

2. boolean addAll(int index, Collection c)

This method is used to insert all elements in the collection c into the list at the specified position.

List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list2.add("Apple");
list2.add("Banana");
list1.addAll(0, list2);

3. Object get(int index)

This method is used to retrieve an element at a specific position in the list.

List<String> list = new ArrayList<String>();
list.add("Apple");
list.get(0); // Returns "Apple"

4. int indexOf(Object o)

This method returns the index of the first occurrence of the specified element in the list.

List<String> list = new ArrayList<String>();
list.add("Apple");
list.indexOf("Apple"); // Returns 0

5. Object remove(int index)

This method is used to remove an element at a specific position.

List<String> list = new ArrayList<String>();
list.add("Apple");
list.remove(0); // Removes "Apple" from the list

Conclusion

That's a brief overview of the List interface in Java. There are many more methods available in this interface, and you can experiment with them as per your needs. Understanding the List interface is crucial when it comes to managing collections of data in Java. So, make sure to practice and get a solid grasp of it.