Tag: Explain the different lists in collection in Java
Values added to the list is based on the index position and it is ordered by index position. Duplicates are allowed.
Types of Lists are:
Array List:
- Fast iteration and fast Random Access.
- It is an ordered collection (by index) and not sorted.
- It implements Random Access Interface.
Example:
public class Fruits {
public static void main(String[] args) {
ArrayList < String > names = new ArrayList < String > ();
names.add(“apple”);
names.add(“cherry”);
names.add(“kiwi”);
names.add(“banana”);
names.add(“cherry”);
System.out.println(names);
}
}
Output:
[Apple, cherry, kiwi, banana, cherry]
From the output, Array List maintains the insertion order and it accepts the duplicates. But not sorted.
Vector:
It is same as Array List.
- Vector methods are synchronized.
- Thread safety.
- It also implements the Random Access.
- Thread safety usually causes a performance hit.
Example:
public class Fruit {
public static void main(String[] args) {
Vector < String > names = new Vector < String > ();
names.add(“cherry”);
names.add(“apple”);
names.add(“banana”);
names.add(“kiwi”);
names.add(“apple”);
System.out.println(“names”);
}
}
Output:
[cherry,apple,banana,kiwi,apple]
Vector also maintains the insertion order and accepts the duplicates.
Linked List:
- Elements are doubly linked to one another.
- Performance is slow than Array list.
- Good choice for insertion and deletion.
- In Java 5.0 it supports common queue methods peek( ), Pool ( ), Offer ( ) etc.
Example:
Output
[ banana,cherry,apple,kiwi,banana]
Maintains the insertion order and accepts the duplicates.