DEV Community

Janardhan Pulivarthi
Janardhan Pulivarthi

Posted on • Edited on

Day 10 of 100 - Java: Collections

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.

  1. It offers positional access to elements either by the index or looping over (ListIterator) the items in the List.
  2. 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();
Enter fullscreen mode Exit fullscreen mode

📝 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);
}
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode
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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)