Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Java Collections Overview

Tech 1

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 collections
    • List: Ordered, allows duplicates
      • ArrayList: List implementation (fast query, slow add/remove)
      • LinkedList: List implementation (slow query, fast add/remove)
    • Set: Unordered, no duplicates
      • HashSet: Set implementation (no sorting)
      • TreeSet: Set implementation (auto-sorts elements)
(2) Dual-Column Hierarchy
  • Map: Root interface for key-value pair collections
    • HashMap
    • TreeMap

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 element
  • int size(): Get number of elements
  • contains(Object o): Check if element exists
  • isEmpty(): Check if collection is empty
  • clear(): Remove all elements
  • remove(Object o): Remove specified element
  • Object[] toArray(): Convert to array
  • Iterator<E> iterator(): Iterate over elements
    • hasNext(): Check for next element
    • next(): 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 index
  • E set(int index, E element): Replace element at index
  • E get(int index): Get element at index
  • int indexOf(Object o): First occurrence index
  • int lastIndexOf(Object o): Last occrurence index
  • List<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:

  1. Get hash code of element a via hashCode()
  2. Calculate position in hash table
  3. If position is empty, store directly
  4. If position has data, compare equality using equals()
  5. 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 pair
  • V get(Object key): Get value by key
  • int size(): Get number of pairs
  • V put(K key, V value): Replace value if key exists
  • boolean containsKey(Object key): Check if key exists
  • boolean containsValue(Object value): Check if value exists
  • V remove(Object key): Remove pair by key
  • void clear(): Clear all pairs
  • Set<K> keySet(): Get all keys
  • Collection<V> values(): Get all values
  • Set<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 pair
  • String 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

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.