List interface represents an ordered collection of elements. It is like a dynamic array that can grow or shrink as needed. It maintains the insertion order of elements and allows duplicate elements.
List Interface:List.List implementations can automatically resize themselves to accommodate new elements.List interface is implemented by several classes, each with its own performance characteristics. The most common ones are:
ArrayList: A resizable array implementation. It provides fast random access (getting elements by index) but can be slower for insertions and deletions in the middle of the list.LinkedList: Implemented using a doubly linked list. It offers efficient insertions and deletions at any position but slower random access compared to ArrayList.Vector: Similar to ArrayList, but it’s synchronized, making it thread-safe but potentially less performant in single-threaded environments. (It’s generally recommended to use ArrayList with explicit synchronization if thread safety is needed).
Here’s a look at some of the essential methods you’ll encounter when working with List implementations:
| Method | Description |
|---|---|
void add(int index, E element) |
Inserts the specified element at the specified position in the list. |
boolean add(E e) |
Appends the specified element to the end of the list. |
E get(int index) |
Returns the element at the specified position in the list. |
E set(int index, E element) |
Replaces the element at the specified position in the list with the specified element. |
E remove(int index) |
Removes the element at the specified position in the list. |
boolean remove(Object o) |
Removes the first occurrence of the specified element from the list, if it is present. |
int size() |
Returns the number of elements in the list. |
boolean isEmpty() |
Returns true if the list contains no elements. |
boolean contains(Object o) |
Returns true if the list contains the specified element. |
int indexOf(Object o) |
Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not contain the element. |
int lastIndexOf(Object o) |
Returns the index of the last occurrence of the specified element in the list, or -1 if the list does not contain the element. |
void clear() |
Removes all of the elements from the list. |
Iterator<E> iterator() |
Returns an iterator over the elements in the list in proper sequence. |
List<E> subList(int fromIndex, int toIndex) |
Returns a view of the portion of this list between the specified fromIndex, inclusive, and toIndex, exclusive. |
Object[] toArray() |
Returns an array containing all of the elements in the list in proper sequence. |
ArrayList is not inherently thread-safe. If multiple threads access and modify an ArrayList concurrently without external synchronization, it can lead to unexpected behavior. For thread-safe dynamic arrays, consider using Vector or Collections.synchronizedList(new ArrayList<>()).
package arraylist;
import java.util.ArrayList;
import java.util.Collections;
public class ArrayListExample1 {
public static void main(String[] args) {
// Create an ArrayList
ArrayList<String> list = new ArrayList<>();
// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Adding element at a specific index
list.add(1, "Date");
// Accessing elements
System.out.println("Element at index 1: " + list.get(1));
// Removing elements
list.remove("Banana");
list.remove(1);
// Updating elements
list.set(1, "Elderberry");
// Iterating through the list
for (String fruit : list) {
System.out.println(fruit);
}
// Checking if the list contains an element
if (list.contains("Apple")) {
System.out.println("Yes! Apple is in the list.");
}
// Getting the size of the list
System.out.println("Size of list: " + list.size());
// Sorting the list
Collections.sort(list);
System.out.println("Sorted list: " + list);
// Converting to an array
String[] array = list.toArray(new String[0]);
System.out.println("Array: " + String.join(", ", array));
// Clearing the list
list.clear();
System.out.println("Size after clear: " + list.size());
}
}
Element at index 1: Date
Apple
Elderberry
Apple is in the list.
Size of list: 2
Sorted list: [Apple, Elderberry]
Array: Apple, Elderberry
Size after clear: 0
In this example, we will create a Student class and store multiple Student objects in an ArrayList.
package arraylist;
class Student {
String name;
int rollNumber;
double grade;
Student(String name, int rollNumber, double grade) {
this.name = name;
this.rollNumber = rollNumber;
this.grade = grade;
}
@Override
public String toString() {
return "Student{name='" + name + "', rollNumber=" + rollNumber
+ ", grade=" + grade + '}';
}
}
package arraylist;
import java.util.ArrayList;
public class StudentArrayList {
public static void main(String[] args) {
ArrayList<Student> students = new ArrayList<>();
// Adding Student objects to the ArrayList
students.add(new Student("John Doe", 1, 85.5));
students.add(new Student("Jane Smith", 2, 92.3));
students.add(new Student("Emily Johnson", 3, 78.9));
// Iterating through the ArrayList and printing each Student
for (Student student : students) {
System.out.println(student);
}
// Accessing a specific Student
Student firstStudent = students.get(0);
System.out.println("First student: " + firstStudent);
// Removing a Student
students.remove(1); // Removes the student at index 1
// Printing the list after removal
System.out.println("List after removal:");
for (Student student : students) {
System.out.println(student);
}
}
}
Student{name='John Doe', rollNumber=1, grade=85.5}
Student{name='Jane Smith', rollNumber=2, grade=92.3}
Student{name='Emily Johnson', rollNumber=3, grade=78.9}
First student: Student{name='John Doe', rollNumber=1, grade=85.5}
List after removal:
Student{name='John Doe', rollNumber=1, grade=85.5}
Student{name='Emily Johnson', rollNumber=3, grade=78.9}
To store different types of objects in a single ArrayList, You typically store them as instances of a common superclass or implement a common interface.
This allows you to leverage polymorphism to manage different types of objects uniformly.
Let’s create a superclass Animal and two subclasses Dog , and Cat.
class Animal {
String name;
Animal(String name) {
this.name = name;
}
void sound() {
System.out.println("Some generic animal sound");
}
}
class Dog extends Animal {
Dog(String name) {
super(name);
}
@Override
void sound() {
System.out.println("Woof");
}
}
class Cat extends Animal {
Cat(String name) {
super(name);
}
@Override
void sound() {
System.out.println("Meow");
}
}
ArrayList to Store Different Types of AnimalWe can create an ArrayList to store objects of type Animal, which will allow us to store both Dog and Cat objects.
package arraylist.animal;
import java.util.ArrayList;
import java.util.List;
public class AnimalArrayList {
public static void main(String[] args) {
List<Animal> animals = new ArrayList<>();
// Adding different types of Animal objects to the ArrayList
animals.add(new Dog("Buddy"));
animals.add(new Cat("Whiskers"));
animals.add(new Dog("Rex"));
animals.add(new Cat("Mittens"));
// Iterating through the ArrayList and calling the sound method
for (Animal animal : animals) {
System.out.println("Name: " + animal.name);
animal.sound();
}
}
}
Name: Buddy
Woof
Name: Whiskers
Meow
Name: Rex
Woof
Name: Mittens
Meow
You must be logged in to submit a review.