Sub topic 1
What the Collections Framework Is
Almost every program has to keep track of a group of things. A shop keeps a list of orders. A game keeps a set of players. A phone keeps contacts that you look up by name. Java gives you one toolkit for all of these jobs, called the Collections Framework. This chapter explains what that toolkit is, why it exists, and how its parts fit together. Later chapters cover each part in detail.
Why arrays are not enough
You already know arrays. An array is a fixed-size block of slots that all hold the same type of value. Arrays are fast and simple, but they have one big limit: their size is fixed when you create them.
Here is what happens when an array runs out of room:
import java.util.Arrays;
public class ArrayLimit {
public static void main(String[] args) {
String[] names = new String[2];
names[0] = "Ana";
names[1] = "Ben";
// names[2] = "Cara"; // would throw ArrayIndexOutOfBoundsException
// To add a third name, build a bigger array and copy everything over
String[] bigger = new String[3];
System.arraycopy(names, 0, bigger, 0, names.length);
bigger[2] = "Cara";
System.out.println(Arrays.toString(bigger)); // [Ana, Ben, Cara]
}
}That is a lot of work to add one name. Arrays also give you no built-in way to do these common jobs:
- Remove an item and close the gap.
- Check whether a value is already present.
- Block duplicate values.
- Look up a value by a name instead of a number.
You could write all of this code yourself, but you would have to write it again in every program. The Collections Framework already has it written and tested for you.
The same job with a collection
A collection is an object that holds a group of other objects, called its elements. Here is the same task using ArrayList, which is one kind of collection:
import java.util.ArrayList;
import java.util.List;
public class ListGrows {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
names.add("Ben");
names.add("Cara"); // no size limit to worry about
System.out.println(names); // [Ana, Ben, Cara]
System.out.println(names.contains("Ben")); // true
names.remove("Ben");
System.out.println(names); // [Ana, Cara]
}
}The list grows when you need more room. It can also search for a value and remove an item, and each of those jobs takes one method call.
The three parts of the framework
A framework is a set of pieces designed to work together. The Collections Framework lives in the java.util package and has three kinds of pieces.
- Interfaces. An interface is a type that lists methods but does not say how they work. In this framework, interfaces describe what a collection can do. Examples:
Collection,List,Set,Map. - Implementations. An implementation is a class that does the actual work behind an interface. Examples:
ArrayList,HashSet,HashMap. - Algorithms. These are ready-made helper methods, such as sorting or finding the largest value. Most of them are static methods in the
Collectionsclass (note the "s" at the end).
You can think of an interface as a job description and an implementation as a worker hired to do that job. Two workers can do the same job in different ways. One might be faster at some tasks, and another might keep things in sorted order.
How the interfaces fit together
The diagram below shows the main interfaces and the classes that implement them. Arrows point from a general type to a more specific one.
Here is what each interface means:
- Iterable means "you can loop over me with a for-each loop."
- Collection is the root interface for groups of single elements.
- List is an ordered sequence. It allows duplicates, and you can reach each element by its position.
- Set holds each element at most once. Adding a duplicate does nothing.
- Queue holds elements waiting to be processed, usually first in, first out. This tutorial does not cover queues in depth.
- Map stores pairs. Each key points to one value, the way a word in a dictionary points to its meaning.
Notice that Map stands apart in the diagram. A map holds pairs, not single elements, so it does not extend Collection. It is still part of the framework, and people still call it a collection in everyday speech.
This table compares the three interfaces you will use most:
| Interface | What it stores | Duplicates? | How you find an item | Common class |
|---|---|---|---|---|
| List | Elements in order | Allowed | By position (index) | ArrayList |
| Set | Unique elements | Not allowed | By asking "is it in here?" | HashSet |
| Map | Key-value pairs | Keys unique, values may repeat | By key | HashMap |
What every Collection can do
Because List, Set, and Queue all extend Collection, they share a core set of methods:
| Method | What it does |
|---|---|
| add(e) | Adds an element; returns true if the collection changed |
| remove(o) | Removes one matching element; returns true if one was found |
| contains(o) | Returns true if the element is present |
| size() | Returns the number of elements |
| isEmpty() | Returns true if there are no elements |
| clear() | Removes all elements |
The next program writes one method that works with any Collection. It then calls that method with a list and with a set. The method calls are the same, but each implementation follows its own rules.
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
public class CollectionDemo {
static void fill(Collection<String> c) {
c.add("red");
c.add("blue");
c.add("red"); // a duplicate
}
public static void main(String[] args) {
Collection<String> list = new ArrayList<>();
Collection<String> set = new HashSet<>();
fill(list);
fill(set);
System.out.println("List size: " + list.size()); // 3, lists keep duplicates
System.out.println("Set size: " + set.size()); // 2, sets drop duplicates
System.out.println(set.contains("blue")); // true
set.remove("blue");
System.out.println(set.size()); // 1
list.clear();
System.out.println(list.isEmpty()); // true
}
}The fill method does not know or care which class it receives. This is a key idea in the framework.
Program to the interface
Look again at this line:
import java.util.ArrayList;
import java.util.List;
public class InterfaceType {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Ana");
System.out.println(names); // [Ana]
}
}The variable's type is the interface List, but the object is an ArrayList. This style is called programming to the interface. It has two benefits:
- You can switch to a different implementation, such as
LinkedList, by changing one word. The rest of your code keeps working. - Methods that accept
ListorCollectionwork with many classes, so you can reuse them.
A first look at Map and the helper algorithms
Maps use different methods because they work with pairs. You add with put(key, value) and read with get(key). The Collections class adds ready-made algorithms such as sort and max.
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class FirstLook {
public static void main(String[] args) {
Map<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");
System.out.println(capitals.get("Japan")); // Tokyo
List<String> cities = new ArrayList<>();
cities.add("Tokyo");
cities.add("Paris");
cities.add("Lima");
Collections.sort(cities);
System.out.println(cities); // [Lima, Paris, Tokyo]
System.out.println(Collections.max(cities)); // Tokyo
}
}Collections hold objects
Collections store objects, not primitive values like int or double. To store numbers, Java uses wrapper classes such as Integer and Double. You write List<Integer>, not List<int>. Java converts between int and Integer for you most of the time. A later chapter shows where that automatic conversion can surprise you.
Summary
- The Collections Framework is a set of interfaces, implementations, and algorithms in
java.util. - Collections grow and shrink as needed, unlike arrays.
Listkeeps order and allows duplicates.Setkeeps only unique elements.Maplinks keys to values.Mapis part of the framework but does not extendCollection.- Declare variables with interface types so you can swap implementations easily.
Exercise
You need to store the usernames of people who signed up for an event, and each person may sign up only once. Which interface fits best: List, Set, or Map? Why?
Show answer
Set. A Set holds each element at most once, so adding a username that is already present has no effect. A List would allow the same name twice, and a Map is for key-value pairs, which this task does not need.
Exercise
In the CollectionDemo program, the fill method adds "red", "blue", and "red" to both collections. Why does list.size() print 3 while set.size() prints 2?
Show answer
An ArrayList allows duplicates, so it keeps both copies of "red". A HashSet does not allow duplicates, so its second add("red") does nothing (it returns false). The method calls are the same, but each implementation follows the rules of its own interface.
Exercise
Is the following statement true or false? "Map is a sub-interface of Collection, so a HashMap can be passed to a method that takes a Collection parameter."
Show answer
False. Map does not extend Collection because it stores key-value pairs instead of single elements. Passing a HashMap to a method that expects a Collection causes a compile error.