The List Interface

The List Interface

The List interface in Java is used to define an ordered collection of elements. In other words, a List is an ordered sequence of elements that can contain duplicates. The elements in a List can be accessed by their index position, and it provides methods to add, remove, and update elements in the list.

The List interface extends the Collection interface, and it defines several additional methods that allow you to perform operations such as getting and setting elements by index, searching for an element, and sorting the list.

Some of the commonly used List implementations in Java include:

ArrayList: This is a resizable array implementation of the List interface. It is backed by an array and provides fast random access to its elements. However, it is not suitable for frequent insertions or deletions, as it requires shifting of elements to maintain the order.

LinkedList: This is a doubly linked list implementation of the List interface. It provides fast insertion and deletion of elements at the beginning or end of the list, but accessing elements by index is slower compared to an ArrayList.

Vector: This is similar to ArrayList, but it is synchronized and therefore thread-safe. However, it is slower compared to ArrayList as it requires acquiring and releasing locks to ensure thread safety.

Stack: This is a subclass of Vector and provides methods to implement the stack data structure.

Example usage of List interface:

List<String> fruits = new ArrayList<>();

fruits.add(“Apple”);

fruits.add(“Banana”);

fruits.add(“Orange”);

System.out.println(fruits); // Output: [Apple, Banana, Orange]

System.out.println(fruits.get(1)); // Output: Banana

fruits.remove(2);

System.out.println(fruits); // Output: [Apple, Banana]

In the above example, we create an ArrayList of strings and add three elements to it. We then print the list, get the element at index 1, and remove the element at index 2. Finally, we print the list again to verify that the element was removed.

Apply for Core Java Developer Certification Now!!

https://www.vskills.in/certification/certified-core-java-developer

Back to Tutorial

Share this post
[social_warfare]
Collections Interface
The Queue Interface

Get industry recognized certification – Contact us

keyboard_arrow_up