Collection framework in Java

  • Collections can work(hold) only with Objects, primitives are not allowed.
  • Collections framework heavily utilize generics concept. For example, if you want to create ArrayList which can hold a collection of Strings, we can do it like this: ArrayList<String> list = new ArrayList<>();
    If you don’t specify a type it will assume as a collection of Objects.
  • It’s common to use polymorphic way of creating instances from collections. ex: List<String> list = new ArrayList<>();

List interface

As you can see in the above scheme, List is an interface that has 3 concrete classes. The List is a dynamic size ordered data structure. It allows duplicate values.

// import statements and valid code aboveint[] numberArray = new int[3];
numberArray[0] = 1;
numberArray[1] = 3;
numberArray[2] = 7;
System.out.println(Arrays.toString(numberArray)); // [1, 3, 7]
List<Integer> colorsList = new ArrayList<>();
System.out.println(colorsList); // [1, 3, 7]
  1. When we created an array of int we specify a size because an array is a fixed-size data structure, however, we don’t specify a size in the collections. We can think that collections have a dynamic size.
  2. As you can see in the List example to specify the data type of it we need to use <> operator. It uses generics in java.
  3. An array can be created as a primitive data type but Collections do not allow primitives, they can hold only objects.

Set Interface

Set does not allow duplicate values. There is no get(index) method in the Set interface. Overall, the performance of Set implementation classes is very high. It has three main implementations: HashSet, LinkedHashSet, TreeSet.

Queue, Stack, and Dequeue

These collections are designed for holding elements prior to processing.

offer(e) adds to the back, poll() removes from the head
  1. offer(e) adds a new element to the back of the queue if possible otherwise. it will return false.
  2. poll() method will remove the element from the head and return it.
  3. peek() method returns, but do not remove, the head of the queue.
Photo by Mick Haupt on Unsplash
  1. push(e) Pushes an item onto the top of this stack.
  2. pop() Removes the object at the top of this stack and returns that object as the value of this function.
  3. peek() method returns an object from the top, but do not remove it.

Map interface

The map is a key value based data structure. In some programming languages, it’s known as a dictionary. Keys are unique in the map. The map is part of the collection framework(it does not extend Collection or Iterable).

Diagram of the Map and some of its implementations



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store