Introduction to Java Collections Framework
The Java Collections Framework provides a unified architecture for storing and manipulating groups of objects. Understanding collections is essential for efficient data management.
What is the Collections Framework?
The Collections Framework is a set of classes and interfaces that implement commonly reusable collection data structures like lists, sets, and maps.
Core Interfaces:
1. Collection - Root interface for all collections
2. List - Ordered collection (allows duplicates)
3. Set - Collection with no duplicates
4. Queue - Collection for holding elements prior to processing
5. Map - Object that maps keys to values
ArrayList:
Resizable array implementation:
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("JavaScript");
LinkedList:
Doubly-linked list implementation:
LinkedList<Integer> numbers = new LinkedList<>();
numbers.add(1);
numbers.addFirst(0);
numbers.addLast(2);
HashSet:
Set that uses hash table:
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Duplicate not added
HashMap:
Key-value pairs:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("John", 95);
scores.put("Sarah", 87);
int johnScore = scores.get("John");
Common Operations:
- add() - Add element
- remove() - Remove element
- contains() - Check if element exists
- size() - Get number of elements
- clear() - Remove all elements
- isEmpty() - Check if empty
Iterating Collections:
Using for-each loop:
for (String item : list) {
System.out.println(item);
}
Using Iterator:
Iterator<String> it = list.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
When to Use Which Collection:
- ArrayList: Fast access by index, slower insertion/deletion
- LinkedList: Fast insertion/deletion, slower random access
- HashSet: Fast lookup, no order, no duplicates
- TreeSet: Sorted set
- HashMap: Fast key-value lookups
- TreeMap: Sorted key-value pairs
Best Practices:
- Use interface types in declarations (List, Set, Map)
- Choose right collection for your needs
- Use generics for type safety
- Consider thread-safety requirements
Mastering collections makes your Java code more efficient and maintainable!
Comments
Post a Comment