Java Collections Framework

What is a Collection?

A collection is a group of items. In Java, a collection is used to store and work with many objects together.

Think about a shopping basket. You can put apples, bananas, or milk in it. You can also remove them or check if an item is in the basket. Java collections work the same way.

Main Interfaces in the Java Collections Framework

Common Classes

When to Use What?

Examples from Daily Life

Code Examples

// Using ArrayList
List shoppingList = new ArrayList<>();
shoppingList.add("Milk");
shoppingList.add("Bread");
shoppingList.add("Milk"); // Duplicate allowed

// Using HashSet
Set uniqueHobbies = new HashSet<>();
uniqueHobbies.add("Reading");
uniqueHobbies.add("Swimming");
uniqueHobbies.add("Reading"); // Duplicate ignored

// Using HashMap
Map contacts = new HashMap<>();
contacts.put("Alice", "12345");
contacts.put("Bob", "67890");

// Using Queue
Queue bankLine = new LinkedList<>();
bankLine.add("Customer1");
bankLine.add("Customer2");
System.out.println(bankLine.poll()); // Customer1
  

Conclusion

Java Collections Framework makes it easy to handle groups of data. Choose the right collection for your task. Practice a lot and try small projects!

Good luck and happy coding! 😊