Day 10 of 100 - Java: Collections
Janardhan Pulivarthi
Posted on January 18, 2022
List
public interface List<E> extends Collection<E>
An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted.
- It offers positional access to elements either by the index or looping over (ListIterator) the items in the
List
. - User has precise control over where items are placed in the
List
.
The common class that implements List
interface is ArrayList
.
https://docs.oracle.com/javase/9/docs/api/java/util/List.html
ArrayList
public class ArrayList<E> implements List<E>
Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null.
Methods
-
add(int index, E element)
- Inserts the specified element at the specified position in this list. -
add(E e)
- Appends the specified element to the end of this list. -
get(int index)
- Returns the element at the specified position in this list. -
contains(Object o)
- Returns true if this list contains the specified element
Example,
ArrayList temperatures = new ArrayList();
temperatures.add(98);
temperatures.add(82);
temperatures.add(93);
temperatures.get(0);
temperatures.remove(0);
// clear the whole ArrayList
temperatures.clear();
📝 We do not need to specify the initial array size, like
int[] myArray = new int[100];
https://docs.oracle.com/javase/9/docs/api/java/util/ArrayList.html
Loop over the Collections
for (String item: list) {
System.out.println(item);
}
Stack vs Queue
In a queue, you would be served in First in First Out.
While, in a stack it is Last in First Out like stack of documents.
Stack papers = new Stack();
papers.push("Pink");
papers.push("White");
String businessPaper = (String) papers.pop();
System.out.println(businessPaper);
Queue orders = new LinkedList();
orders.add("Order1");
orders.add("Order2");
orders.add("Order3");
System.out.print(orders.poll()); //Order1
System.out.print(orders.poll()); //Order2
System.out.print(orders.poll()); //Order3
Generics
With and without generics
- List list = new ArrayList();
+ List<String> list = new ArrayList<String>();
list.add("hello");
- String s = (String) list.get(0);
+ String s = list.get(0); // no cast
Polymorphism with Collections
ArrayList<Media> playlist = new ArrayList();
Video coolVideo = new Video();
Audio coolAudio = new Audio();
playlist.add(coolVideo);
playlist.add(coolAudio);
// We can use a common type to cast output
Media media = playlist.get(0);
media.play();
Posted on January 18, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.