Fundamentals 13 min read

Java Collection Framework Overview with Code Examples

This article explains the Java collection class diagram, distinguishes concrete classes, abstract classes, and interfaces, describes Iterator and ListIterator behavior, and provides detailed code demonstrations of HashSet, ArrayList, ListIterator, and WeakHashMap usage along with their outputs.

Java Captain
Java Captain
Java Captain
Java Collection Framework Overview with Code Examples

The article begins with a class diagram of Java collection classes, where solid borders denote concrete implementation classes (e.g., ArrayList, LinkedList, HashMap), dashed borders denote abstract classes (e.g., AbstractCollection, AbstractList, AbstractMap), and dotted borders denote interfaces (e.g., Collection, Iterator, List).

It points out that all collection classes implement the Iterator interface, which provides hasNext() , next() , and remove() methods, and that ordered collections also implement the ListIterator (or LinkedIterator ) interface, adding add() , previous() , and hasPrevious() for bidirectional traversal.

The text highlights the convenience of abstract classes, which supply default implementations so developers can extend them rather than implementing every method of an interface from scratch.

2.1 HashSet – HashSet implements the Set interface, disallows duplicate elements, and stores elements using a hash table without preserving insertion order. Example code HashSetDemo demonstrates adding elements, iterating with an Iterator , using a for‑each loop, and printing the set via toString() :

package edu.sjtu.erplab.collection;

import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetDemo {
    public static void main(String[] args) {
        Set
set = new HashSet
();
        set.add("a");
        set.add("b");
        set.add("c");
        set.add("c");
        set.add("d");
        Iterator
iter = set.iterator();
        while (iter.hasNext()) {
            System.out.print(iter.next() + " ");
        }
        System.out.println();
        for (String e : set) {
            System.out.print(e + " ");
        }
        System.out.println();
        System.out.println(set);
    }
}

Another example, SetTest , reads words from a file (or resource) into a HashSet and prints a few elements and the set size:

package edu.sjtu.erplab.collection;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

public class SetTest {
    public static void main(String[] args) throws FileNotFoundException {
        Set
words = new HashSet
();
        InputStream inStream = SetTest.class.getResourceAsStream("Alice.txt");
        Scanner in = new Scanner(inStream);
        while (in.hasNext()) {
            words.add(in.next());
        }
        Iterator
iter = words.iterator();
        for (int i = 0; i < 5; i++) {
            if (iter.hasNext())
                System.out.println(iter.next());
        }
        System.out.println(words.size());
    }
}

2.2 ArrayList – ArrayList implements List , allows duplicate elements, and preserves insertion order. The example ArrayListDemo shows adding elements, iterating with an Iterator , using a for‑each loop, and printing the list:

package edu.sjtu.erplab.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ArrayListDemo {
    public static void main(String[] args) {
        List
arrList = new ArrayList
();
        arrList.add("a");
        arrList.add("b");
        arrList.add("c");
        arrList.add("c");
        arrList.add("d");
        Iterator
iter = arrList.iterator();
        while (iter.hasNext()) {
            System.out.print(iter.next() + " ");
        }
        System.out.println();
        for (String e : arrList) {
            System.out.print(e + " ");
        }
        System.out.println();
        System.out.println(arrList);
    }
}

2.3 ListIterator – Demonstrated with LinkedListTest , showing how a ListIterator can insert elements from one list into another at specific positions and how to remove elements while iterating.

package edu.sjtu.erplab.collection;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

public class LinkedListTest {
    public static void main(String[] args) {
        List
a = new ArrayList
();
        a.add("a");
        a.add("b");
        a.add("c");
        System.out.println(a);
        List
b = new ArrayList
();
        b.add("d");
        b.add("e");
        b.add("f");
        b.add("g");
        System.out.println(b);
        ListIterator
aIter = a.listIterator();
        Iterator
bIter = b.iterator();
        while (bIter.hasNext()) {
            if (aIter.hasNext())
                aIter.next();
            aIter.add(bIter.next());
        }
        System.out.println(a);
        bIter = b.iterator();
        while (bIter.hasNext()) {
            bIter.next();
            if (bIter.hasNext()) {
                bIter.next();
                bIter.remove();
            }
        }
        System.out.println(b);
        a.removeAll(b);
        System.out.println(a);
    }
}

2.4 HashMap – Mentioned briefly with a reference to another blog post.

2.5 WeakHashMapDemo – Shows how keys held only by weak references can be garbage‑collected. The program populates a WeakHashMap with Key and Value objects, forces garbage collection, and prints the map before and after collection. The output illustrates that keys without strong references are reclaimed, while values remain because they are still strongly reachable through the map entries.

package edu.sjtu.erplab.collection;

import java.util.WeakHashMap;

public class WeekHashMapDemo {
    public static void main(String[] args) {
        int size = 100;
        if (args.length > 0) {
            size = Integer.parseInt(args[0]);
        }
        Key[] keys = new Key[size];
        WeakHashMap
whm = new WeakHashMap
();
        for (int i = 0; i < size; i++) {
            Key k = new Key(Integer.toString(i));
            Value v = new Value(Integer.toString(i));
            if (i % 3 == 0) {
                keys[i] = k; // strong reference
            }
            whm.put(k, v);
        }
        System.out.println(whm);
        System.out.println(whm.size());
        System.gc();
        try { Thread.sleep(4000); } catch (InterruptedException e) { e.printStackTrace(); }
        System.out.println(whm);
        System.out.println(whm.size());
    }
}

class Key {
    String id;
    public Key(String id) { this.id = id; }
    public String toString() { return id; }
    public int hashCode() { return id.hashCode(); }
    public boolean equals(Object r) { return (r instanceof Key) && id.equals(((Key) r).id); }
    public void finalize() { System.out.println("Finalizing Key " + id); }
}

class Value {
    String id;
    public Value(String id) { this.id = id; }
    public String toString() { return id; }
    public void finalize() { System.out.println("Finalizing Value " + id); }
}

The article concludes with a comparison image summarizing the relationships among the collection classes and includes a promotional QR code for a Java technology sharing channel.

javaCollectionsData StructuresArrayListIteratorHashSetWeakHashMap
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.