Java Collections Framework
The Collections Framework provides interfaces and classes for keeping and processing groups of objects. Different collection types organize values in different ways, so we choose a type based on how the program uses its data.
Why Do We Need This?
A shopping list may need repeated items in a chosen order. A list of registered usernames may need uniqueness. A lookup from product code to price needs a key and a value.
Main Ideas
| Concept | What it means |
|---|---|
| List | Keeps a sequence with indexed positions and allows duplicates |
| Set | Keeps elements without duplicates under its equality or comparison rules |
| Queue | Keeps elements waiting to be processed according to an ordering rule |
| Map | Associates keys with values; Map does not extend Collection |
| Iterator | Visits elements through a common traversal interface |
Simple Working Example
Run this program on its own. All required imports and classes are included.
import java.util.ArrayList;
import java.util.List;
public class HelloWorld {
public static void main(String[] args) {
List<String> topics = new ArrayList<>();
topics.add("Arrays");
topics.add("Collections");
for (String topic : topics) {
System.out.println(topic);
}
}
}Output
Arrays
CollectionsList describes the operations available through topics. ArrayList supplies an implementation. Generic type arguments such as String help the compiler check the values we use.
Topics in This Section
Easy Way to Remember
An interface describes a contract; an implementation supplies its behavior. Ordering, null support, mutability, and thread safety depend on the chosen implementation.
See you in next page....??