Java Collections Library
The Java Collections Framework is a set of interfaces and classes in the java.util package for storing and working with groups of objects. Instead of writing your own data structures, you reuse well tested ones that are already part of the JDK. This lecture introduces the core interfaces, the concrete classes you actually create, and how to choose the right collection for a given problem.
In Unit 1 we focus on the Collection hierarchy: Set, SortedSet, and List. Java has a second hierarchy, Map, for storing key to value pairs. Maps build on the ideas here, so we save them for Unit 2.
By the end of this lecture you should be able to:
- Describe the
Collectionhierarchy and the interfaces in it. - Explain the difference between a
Set,SortedSet, andList. - Create, add to, display, and iterate over a
Listand aSet. - Choose an appropriate collection for a storage problem, and judge whether a collection an AI tool suggested is a good fit.
The Collections Interfaces
Interface hierarchy summary
The hierarchy we use in Unit 1 is rooted at Collection, which represents a group of objects:
SetextendsCollection. A Set holds no duplicate elements and does not guarantee order.SortedSetextendsSet. A SortedSet keeps its elements in sorted order.
ListextendsCollection. A List allows duplicate elements and maintains insertion order.
Maps come later
Java has a second collections hierarchy, Map, for storing key to value pairs, such as a name mapped to an age. A Map is not a Collection, and it works a little differently. We introduce it in Unit 2, after you are comfortable with Lists and Sets. For now, focus on the Collection hierarchy above.
In Unit 1 we will focus on these three interfaces:
- Set
- SortedSet
- List
AI and collections
When you ask an AI tool to write code that stores data, it will almost always reach for a collection, and often a specific one like ArrayList or HashSet. Understanding this material is essential to evaluating whether the AI chose the right collection for the job. You will be doing exactly that in the labs.
Definitions
Set
- A collection that cannot contain duplicate elements.
- A collection that does not guarantee the order of its elements.
SortedSet
- A collection that cannot contain duplicate elements.
- A collection that is continuously sorted by its elements' natural order or by a custom order.
List
- A collection that can contain duplicate elements.
- A collection that maintains and guarantees the order of its elements.
API
The full reference is the Java 21 API documentation. Bookmark it. You will use it constantly.
The primary methods for the Collection interface:
boolean add(E e)adds an element and returnstrueif the collection changed.boolean contains(Object o)returnstrueif the element is present.Iterator<E> iterator()returns an iterator for looping over the elements.int size()returns the number of elements.
Concrete Implementations
An interface describes what a collection does. A concrete class describes how it does it. You program to the interface but create an instance of a concrete class. Each interface has one common implementation you will use most often:
| Interface | Common implementation | Behavior |
|---|---|---|
Set |
HashSet |
No duplicates, no predictable order |
SortedSet |
TreeSet |
No duplicates, kept in natural sorted order |
List |
ArrayList |
Duplicates allowed, keeps insertion order |
Lists
Create a List
// Legacy (Java 4 and earlier), avoid this
List list = new ArrayList();
// Current (Java 5+)
List<String> list = new ArrayList<String>();
Notice the type on the left of the assignment. It is a best practice to declare variables as an interface (List) rather than a concrete class (ArrayList) whenever possible. This lets you swap the implementation later without changing the rest of your code.
// If the compiler can infer the type, use the empty "diamond" <> (Java 7+)
List<String> list = new ArrayList<>();
Add to a List
The add method appends an element to the end of the list.
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
Display a List
Getting a quick view of a List.
System.out.println(list);
Output
[one, two]
The easiest way to see the contents of a list that is not too big is to pass the list reference variable straight to System.out.println().
Check your understanding
With this technique, what method is called on each element in list?
Answer: toString(). Printing the list calls the list's own toString(), which in turn calls toString() on each element to build the text you see.
Iterating through a List
// Enhanced for-loop (Java 5+), use this!
for (String element : list) {
System.out.println(element);
}
Legacy: Java 1.4 Iterator style (for reference only)
You may encounter this pattern in older codebases. You do not need to write it this way.
for (Iterator iterator = list.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
}
Output
one
two
Complete demo class
package java112.labs1;
import java.util.*;
/**
* @author Eric Knapp
* class ListDemo
*
*/
public class ListDemo {
public void run() {
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
System.out.println(list);
System.out.println();
System.out.println("Enhanced for-loop (Java 5+)");
for (String element : list){
System.out.println(element);
}
}
public static void main(String[] args) {
ListDemo demo = new ListDemo();
demo.run();
}
}
Sets
Create a Set
// Legacy (Java 4 and earlier), avoid this
Set set = new HashSet();
// Current (Java 5+)
Set<String> set = new HashSet<>();
Add to a Set
// What happens to the duplicates?
set.add("one");
set.add("one");
set.add("two");
set.add("two");
set.add("two");
set.add("two");
set.add("three");
set.add("three");
Display a Set
Getting a quick view of a Set, just like a list.
System.out.println(set);
Example output
[one, two, three]
The duplicates are gone. A Set silently ignores any element it already contains, so each value appears only once.
HashSet order is not guaranteed
A HashSet makes no promise about the order of its elements, so the order you see when you print one may differ from the example above and may even change between runs. If you need the elements in a predictable, sorted order, use a TreeSet (a SortedSet) instead.
Iterating through a Set
// Enhanced for-loop (Java 5+), use this!
for (String element : set) {
System.out.println(element);
}
Legacy: Java 1.4 Iterator style (for reference only)
You may encounter this pattern in older codebases. You do not need to write it this way.
for (Iterator iterator = set.iterator(); iterator.hasNext();) {
System.out.println(iterator.next());
}
Complete Set demo
package java112.labs1;
import java.util.*;
/**
* @author Eric Knapp
* class SetDemo
*
*/
public class SetDemo {
public void run() {
Set<String> set = new HashSet<>();
set.add("one");
set.add("one");
set.add("two");
set.add("two");
set.add("two");
set.add("two");
set.add("three");
set.add("three");
System.out.println(set);
System.out.println();
System.out.println("Enhanced for-loop (Java 5+)");
for (String element : set){
System.out.println(element);
}
}
public static void main(String[] args) {
SetDemo demo = new SetDemo();
demo.run();
}
}
Try it
Run SetDemo as written, then change HashSet to TreeSet and run it again. Compare the order of the output. This is the difference between a Set and a SortedSet in action.
Which Collection Should I Use?
Choosing a Collection is a design decision. The right choice depends on two things: the nature of the data you are storing, and how your program needs to use it. Asking a few simple questions upfront will point you to the appropriate type.
| If you need... | Use... | Example |
|---|---|---|
| Items in insertion order, duplicates allowed | List / ArrayList |
Lines read from a file, a to-do list |
| Unique items only, order does not matter | Set / HashSet |
Distinct words found in a document |
| Unique items in sorted order | SortedSet / TreeSet |
Vocabulary words listed alphabetically |
Quick Decision Checklist
Work through these questions when you are unsure which Collection to reach for:
- Do I need duplicates? If yes, use a
List. If no, use aSetorSortedSet. - Does order matter? If insertion order matters, use a
List. If sorted order matters, use aSortedSet. - Does the data need to stay sorted automatically? If yes, use a
TreeSet.
Evaluating an AI suggestion
When an AI tool hands you code that uses a collection, run it through this same checklist. Ask whether the type it chose actually matches the requirements: does the data really allow duplicates, and does order matter? A tool will often default to ArrayList even when a Set or a sorted type would be a better fit. Your job is to catch that.
Coming in Unit 2: Maps
Once you are comfortable with Lists and Sets, Unit 2 introduces the Map hierarchy for storing key to value pairs, such as a word mapped to its count or a student ID mapped to a name. See Java Maps.
Further Readings
- Oracle Collections Tutorial
- Collections in Java (Focus on List and Set)
