Java Collections

Published: September 26, 2015

In Resources.

Overview

Java collections framework is important part of environment. It allows you to create dynamic structures with various performance requirements depending on your needs.

Most basic structure that probably you will be using very frequently is ArrayList. It's simply a dynamic array of type you specify as a generic parameter (since introduction of generics in JDK 1.5).

List<String> list = new ArrayList<>();

list.add("Java");
list.add("Scala");
list.add("Groovy");

for (String str: list) {
  System.out.println(str);
}

Note that:

  • you don't have to specify element type twice (since Java 7) when declaring the structure
  • variable type is different than object being created, this is because variable is declared using base interface

ArrayList also implements Iterable interface which you can to loop through the container as follows:

Iterator<String> it = list.iterator();   
while (it.hasNext()) {
    String str = it.next();  
    System.out.println(str);
}

Other popular collection class types (interfaces) are:

  • Set (unique values container, implementations: HashSet, TreeSet, LinkedHashSet) and
  • Map (key-value storage, implementations: HashMap, TreeMap)

Deprecated / legacy collections

There are some collections that you can find in old Java code but you shouldn't use anymore. They were defined & implemented before standard Collections API has been defined.

Other classes of this kind: Dictionary, Stack.

Introductory materials

Performance

Libraries

Books

  • "Java Generics and Collections" - Maurice Naftalin/Philip Wadler, 2006

See also

Share

follow