Collections Framework

1. Introduction to Collections

1.1 What is the Collections Framework

A framework that provides classes and interfaces for storing and manipulating data.

1.2 Why Use Collections

  • Dynamic size
  • Built-in methods
  • Better performance

1.3 Key Components

  • Interfaces
  • Classes
  • Algorithms

1.4 Collection Hierarchy

  • Collection → List, Set
  • Map (separate hierarchy)

2. List Interface

2.1 Definition

An ordered collection that allows duplicate elements.

2.2 Common Classes

  • ArrayList
  • LinkedList
  • Vector

2.3 Example

import java.util.*;List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("A");System.out.println(list);

2.4 Operations

  • add()
  • remove()
  • get()
  • set()

2.5 ArrayList vs LinkedList

  • ArrayList → faster access
  • LinkedList → faster insertion

3. Set Interface

3.1 Definition

A collection that does not allow duplicate elements.

3.2 Common Classes

  • HashSet
  • LinkedHashSet
  • TreeSet

3.3 Example

Set<Integer> set = new HashSet<>();
set.add(10);
set.add(20);
set.add(10);System.out.println(set);

3.4 Features

  • No duplicates
  • Unordered (HashSet)

4. Map Interface

4.1 Definition

Stores data in key-value pairs.

4.2 Common Classes

  • HashMap
  • LinkedHashMap
  • TreeMap

4.3 Example

Map<Integer, String> map = new HashMap<>();
map.put(1, "A");
map.put(2, "B");System.out.println(map.get(1));

4.4 Operations

  • put()
  • get()
  • remove()

5. Iterators

5.1 Definition

Used to traverse collections.

5.2 Methods

  • hasNext()
  • next()
  • remove()

5.3 Example

Iterator<String> it = list.iterator();while (it.hasNext()) {
    System.out.println(it.next());
}

5.4 ListIterator

Supports forward and backward traversal.


6. Comparable vs Comparator

6.1 Comparable

Used to define natural ordering.

class Student implements Comparable<Student> {
    int age;    public int compareTo(Student s) {
        return this.age - s.age;
    }
}

6.2 Comparator

Used to define custom sorting.

class SortByAge implements Comparator<Student> {
    public int compare(Student a, Student b) {
        return a.age - b.age;
    }
}

6.3 Differences

ComparableComparator
Inside classSeparate class
compareTo()compare()

Conclusion

The Collections Framework is essential for handling data efficiently in Java. By understanding List, Set, Map, iterators, and sorting techniques, beginners can build scalable and efficient applications. Mastering collections is a key step toward becoming a proficient Java developer.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *