Java Collections Overview
Collections
A container for storing multiple objects.
Arrays:
- Fixed length after initialization
1. Collection Categories
- Single-Column Collections: Store individual elements Examples: 1 2 3; Alice Bob
- Dual-Column Collections: Store key-value pairs Examples: name:Alice; age:11
2. Collection Hierarchy
(1) Single-Column Hierarchy
Collection: Root interface for single-column collectionsList: Ordered, allows duplicatesArrayList: List implementation (fast query, slow add/remove)LinkedList: List implementation (slow query, fast add/remove)
Set: Unordered, no duplicatesHashSet: Set implementation (no sorting)TreeSet: Set implementation (auto-sorts elements)
(2) Dual-Column Hierarchy
Map: Root interface for key-value pair collectionsHashMapTreeMap
3. Generics <>
Specifies the data type stored in a collection.
Collections can hold any type, but typically hold one type. Generics enforce this constraint.
Syntax: <DataType>
4. Single-Column Collections
1. Collection
Collection<String> items = new ArrayList<>();
Key Methods:
add(E e): Add an elementint size(): Get number of elementscontains(Object o): Check if element existsisEmpty(): Check if collection is emptyclear(): Remove all elementsremove(Object o): Remove specified elementObject[] toArray(): Convert to arrayIterator<E> iterator(): Iterate over elementshasNext(): Check for next elementnext(): Get next element
Collection<String> items = new ArrayList<>();
items.add("Java");
items.add("Python");
items.add("C++");
Iterator<String> iter = items.iterator();
while (iter.hasNext()) {
String lang = iter.next();
System.out.println(lang);
}
2. List
Ordered, allows duplicates.
Key Methods:
void add(int index, E element): Insert at index
List<String> words = new ArrayList<>();
words.add("apple");
words.add("banana");
words.add(1, "orange");
boolean addAll(int index, Collection<? extends E> c): Add all elements from another collection
List<String> nums = new ArrayList<>();
nums.add("1");
nums.add("2");
words.addAll(2, nums);
E remove(int index): Remove element at indexE set(int index, E element): Replace element at indexE get(int index): Get element at indexint indexOf(Object o): First occurrence indexint lastIndexOf(Object o): Last occrurence indexList<E> subList(int fromIndex, int toIndex): Get sublist (inclusive from, exclusive to)sort(Comparator<? super E> c): Sort with custom comparator
List<Student> students = new ArrayList<>();
students.sort(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
return s1.getId() - s2.getId(); // Ascending by ID
}
});
ArrayList: Based on dynamic array, fast random access. LinkedList: Based on doubly linked list, efficient for add/remove operations.
3. Set
Unordered, no duplicates.
6. HashSet
No sorting. Uses hash table for storage.
Storage Process:
- Get hash code of element
aviahashCode() - Calculate position in hash table
- If position is empty, store directly
- If position has data, compare equality using
equals() - If equal, discard new element; if not, store
Note: Override hashCode() and equals() for custom objects.
7. TreeSet
Auto-sorts elements using a red-black tree (binary search tree).
Storage Principle:
- Each parent node has left (smaller) and right (larger) child nodes
- Elements must have a natural order or a custom comparator
5. Dual-Column Collections
1. Map
Stores key-value pairs; keys are unique, values can repeat.
Example: {id:101, name:Alice, age:18}
2. Map Methods
public static void main(String[] args) {
HashMap<String, Object> userMap = new HashMap<>();
userMap.put("id", 101);
userMap.put("name", "Alice");
userMap.put("age", 18);
System.out.println(userMap);
Object name = userMap.get("name");
System.out.println("Name: " + name);
System.out.println("Size: " + userMap.size());
userMap.put("age", 19);
System.out.println("Updated Map: " + userMap);
System.out.println("Has 'name' key: " + userMap.containsKey("name"));
System.out.println("Has 'Bob' value: " + userMap.containsValue("Bob"));
userMap.remove("name");
System.out.println("After Remove: " + userMap);
Set<String> keys = userMap.keySet();
System.out.println("Keys: " + keys);
Collection<Object> values = userMap.values();
System.out.println("Values: " + values);
iterateMap(userMap);
}
public static void iterateMap(Map<String, Object> map) {
System.out.println("--- Iterate via KeySet ---");
for (String key : map.keySet()) {
Object val = map.get(key);
System.out.println(key + " = " + val);
}
System.out.println("--- Iterate via EntrySet ---");
for (Map.Entry<String, Object> entry : map.entrySet()) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
}
Key Methods:
V put(K key, V value): Add key-value pairV get(Object key): Get value by keyint size(): Get number of pairsV put(K key, V value): Replace value if key existsboolean containsKey(Object key): Check if key existsboolean containsValue(Object value): Check if value existsV remove(Object key): Remove pair by keyvoid clear(): Clear all pairsSet<K> keySet(): Get all keysCollection<V> values(): Get all valuesSet<Map.Entry<K, V>> entrySet(): Get all entries
6. Properties Class
Extends Hashtable, implements Map. Fixed string types; works with IO streams for persistence.
Key Methods:
setProperty(String key, String value): Add string pairString getProperty(String key): Get value by string key
public static void main(String[] args) {
Properties config = new Properties();
config.setProperty("db.url", "jdbc:mysql://localhost:3306/db");
config.setProperty("db.user", "root");
System.out.println(config);
String url = config.getProperty("db.url");
System.out.println("URL: " + url);
Properties systemProps = System.getProperties();
System.out.println("OS Name: " + systemProps.getProperty("os.name"));
}
7. Wrapper Classes
Convert primitive types to objects for collection storage.
| Primitive | Wrapper |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Autoboxing: Automatic conversion from primitive to wrapper Unboxing: Automatic conversion from wrapper to primitive