Java 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 a specific position. The main thing about the list implementations is that they are ordered and allow duplicates.
- ArrayList: ArrayList is like an auto-resizable array. When we add elements, the size of the array grows automatically. The main benefit of an ArrayList is that we can look up any element in constant time. ArrayList is a good choice when a 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 an element to end. |
void |
add(int index, E element) |
It adds an element at index and moves the rest toward the end. |
E |
get(int index) |
It returns the 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 the element at index and moves the rest towards the front. |
E |
set(int index, E e) |
It replaces the element at index and returns original. |
Example:
import java.util.ArrayList; import java.util.List; public class ListExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("India"); // [SD] list.add(0, "China"); // [China,India] System.out.println(list); list.set(1, "USA"); // [China,USA] System.out.println(list); list.remove("China"); // [USA] System.out.println(list); list.remove(0); // [] System.out.println(list); } }
Output:
[China, India] [China, USA] [USA] []