BhauAutomation

Collection in Java

The Collection Framework in Java provides classes and interfaces to store, manage, and manipulate groups of objects efficiently.

What is Collection in Java?

A Collection in Java is a framework providing an architecture to store and manage a group of objects. It includes interfaces (List, Set, Queue, Map) and classes (ArrayList, HashSet, LinkedList, etc.) for efficient data handling.

Example: List Collection

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

public class ListExample {
    public static void main(String[] args) {
        List fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Mango");

        System.out.println(fruits);
    }
}
    

Example: Set Collection

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

public class SetExample {
    public static void main(String[] args) {
        Set numbers = new HashSet<>();
        numbers.add(10);
        numbers.add(20);
        numbers.add(10); // duplicate ignored
        System.out.println(numbers);
    }
}
    

Example: Map Collection

import java.util.HashMap;
import java.util.Map;

public class MapExample {
    public static void main(String[] args) {
        Map marks = new HashMap<>();
        marks.put("Alice", 90);
        marks.put("Bob", 85);
        System.out.println(marks);
    }
}
    

Objectives of Collection Framework

The framework aims to:

- Represent and manipulate dynamic data groups efficiently

- Reduce programming effort using reusable data structures

- Provide high-performance, flexible data handling

Advantages

- Reduces development time

- Provides ready-to-use data structures

- Improves performance with built-in algorithms

Limitations

- Can increase memory overhead in some cases

- Type safety issues in non-generic collections

- Performance trade-offs with certain operations

Hierarchy of Collection Framework

The core interfaces include:

- List: Ordered collection, allows duplicates (ArrayList, LinkedList)

- Set: Unordered, no duplicates (HashSet, TreeSet)

- Queue: FIFO structure (PriorityQueue, LinkedList)

- Map: Stores key-value pairs (HashMap, TreeMap)

Best Practices

- Always use generics for type safety

- Choose the right collection class for your use case

- Prefer interfaces over concrete classes (List, Set, Map)

- Use streams and lambda expressions for cleaner, modern code