ADVERTISEMENT
Google AdSense Slot (headerLeaderboard)

Set your Publisher ID in src/config/ads.ts to display live ads.

Java Tutorial• 7 min read

The Collections Framework: ArrayList, HashMap & HashSet

Generics <T>, dynamic lists, hash-based key-value maps, and set uniqueness

The Java Collections Framework (java.util) provides standardized data structures: ArrayList for resizable lists, HashMap for key-value pairs, and HashSet for unique items.

ArrayList vs HashMap vs HashSet

ArrayList<T>: Dynamic resizable array. Fast random access O(1) by index.

HashMap<K, V>: Stores key-value associations with average O(1) retrieval using put(k, v) and get(k).

HashSet<T>: Stores unique elements, automatically eliminating duplicates.

Using ArrayList and HashMap with Generics
import java.util.*;

public class CollectionsDemo {
    public static void main(String[] args) {
        // Dynamic list
        List<String> courses = new ArrayList<>();
        courses.add("Java Enterprise");
        courses.add("Spring Boot");
        courses.add("PostgreSQL");

        // Key-Value Map
        Map<String, Integer> courseEnrollment = new HashMap<>();
        courseEnrollment.put("Java Enterprise", 2400);
        courseEnrollment.put("Spring Boot", 1850);

        for (String course : courses) {
            int enrolled = courseEnrollment.getOrDefault(course, 0);
            System.out.println(course + ": " + enrolled + " students");
        }
    }
}
ADVERTISEMENT
Google AdSense Slot (inContentBanner)

Set your Publisher ID in src/config/ads.ts to display live ads.

Test Yourself With Exercise

+15 XP

Which collection in Java guarantees that all stored elements are completely unique with zero duplicates?