Java Collections Framework provides a set of interfaces and classes that implement different data structures, algorithms, and utilities for storing and manipulating groups of objects. This document gives an overview of the most commonly used collections in Java.

Common Collections

Here are some of the most commonly used collections in Java:

  • ArrayList: A dynamic array implementation that allows fast random access but slow insertions and deletions.
  • LinkedList: A doubly-linked list implementation that allows fast insertions and deletions but slow random access.
  • HashSet: A set implementation that does not allow duplicate elements and provides constant-time performance for basic operations.
  • HashMap: A map implementation that allows you to associate keys with values and provides constant-time performance for basic operations.
  • TreeSet: A set implementation that maintains its elements in a sorted order.
  • TreeMap: A map implementation that maintains its mappings in a sorted order.

Usage Scenarios

  • Use ArrayList when you need fast random access and the size of the collection is known in advance.
  • Use LinkedList when you need fast insertions and deletions but do not require fast random access.
  • Use HashSet when you need a collection that does not allow duplicate elements.
  • Use HashMap when you need to associate keys with values.
  • Use TreeSet when you need a collection that maintains its elements in a sorted order.
  • Use TreeMap when you need a map that maintains its mappings in a sorted order.

Example

Here's an example of how to use some of the collections:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // ArrayList
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Collections");

        // LinkedList
        LinkedList<String> linkedList = new LinkedList<>(list);

        // HashSet
        Set<String> set = new HashSet<>(list);

        // HashMap
        Map<String, Integer> map = new HashMap<>();
        map.put("Java", 1);
        map.put("Collections", 2);

        // TreeSet
        Set<String> treeSet = new TreeSet<>(list);

        // TreeMap
        Map<String, Integer> treeMap = new TreeMap<>(map);
    }
}

For more information on Java Collections, you can visit the Java Collections Framework documentation.

Images

  • Java Collections
  • Java List
  • Java LinkedList
  • Java Set
  • Java Map
  • Java TreeSet
  • Java TreeMap