Page Content

Tutorials

What are the Goals of Collection Framework in Java?

Collection Framework in Java

The Collection Framework in Java, which offers a cohesive and effective framework for managing collections of objects, is a fundamental component of contemporary Java programming. Before J2SE 1.2, Java used a number of ad hoc classes to store and work with object groups, including Dictionary, Vector, Stack, and Properties. Although these previous classes were useful, they lacked interoperability and a unified concept. By providing a uniform method for managing collections of objects, the Collections Framework was created to overcome these constraints.

What is a Collections Framework?

Java collections are represented and worked with using a single architecture called a collections framework. It standardises the way your programs deal with object groupings. This framework is organised around three primary parts:

Collections Framework in Java
Collections Framework in Java
  1. Interfaces: Various kinds of collections are represented by these abstract data types, which enable manipulation of the collections regardless of the implementation details at play.
  2. Implementations (Classes): The tangible, reusable data structures known as implementations (classes) offer particular implementations of the collection interfaces. Examples of these include dynamic arrays, linked lists, trees, and hash tables.
  3. Algorithms: Methods that carry out practical calculations on objects that implement collection interfaces, including sorting and searching, are called algorithms. These algorithms are polymorphic, which means that several implementations of the relevant interface can employ the same technique.

The addition of generics, autoboxing/unboxing, and the for-each style for loop in JDK 5 greatly improved the framework’s functionality and made it easier to use. Type safety introduced by generics in particular significantly altered the foundation.

Benefits of Collections Framework in Java

The Java Collections Framework provides developers with a number of significant benefits, including:

Benefits of Collections Framework in Java
Benefits of Collections Framework in Java
  • High Performance: Basic collection implementations, such as dynamic arrays, linked lists, trees, and hash tables, are very effective and frequently do not require explicit coding.
  • Interoperability: Because of its standard interface-based design, it offers a high degree of interoperability and enables various collection kinds to collaborate in a similar way.
  • Ease of Extension and Adaptation: because the framework is based on a set of standard interfaces, using the implementations that are offered (e.g., LinkedList, HashSet, TreeSet) or creating custom collection classes is simple.
  • Type Safety: Explicit specification of the data types contained in a collection is made possible by generics, which helps avoid runtime type mismatch problems, which are a major problem in pre-generics programming.
  • Reduced Development Effort: By offering pre-made solutions for typical programming tasks, the framework drastically cuts down on boilerplate code that programmers must write, freeing them up to concentrate on higher-level reasoning.

Core Interfaces: Collection, List, Set, Map

The behaviour and properties of various collection kinds are determined by a number of fundamental interfaces defined by the framework.

The Collection Interface

The Collection interface stands at the top of the collections hierarchy and serves as the foundation for the entire framework. Any class that defines a collection must implement this interface. It is a generic interface, declared as interface Collection<E>, where E specifies the type of objects the collection will hold. Importantly, Collection extends the Iterable interface, meaning all collections can be traversed using the for-each style for loop.

Key methods declared by the Collection interface include:

  1. boolean add(E obj): Adds an object to the collection.
  2. boolean addAll(Collection<? extends E> c): Adds all elements from another collection.
  3. void clear(): Removes all elements from the collection.
  4. boolean contains(Object obj): Checks if an object is an element of the collection.
  5. boolean isEmpty(): Returns true if the collection contains no elements.
  6. boolean remove(Object obj): Removes a specified object.
  7. int size(): Returns the number of elements in the collection.
  8. Iterator<E> iterator(): Returns an iterator to traverse the elements.

Some methods, if not supported by an unmodifiable collection, will throw an UnsupportedOperationException.

The List Interface

The List interface defines a collection that holds a series of elements and extends Collection. Elements are accessible through their zero-based index and are kept in a particular order. Lists permit duplicate items.

Typical List implementations are as follows:

  • ArrayList: A dynamic array that can automatically expand or contract in response to the addition or removal of entries is implemented by the ArrayList.
  • LinkedList: This efficient method of adding or removing members from the ends of a doubly-linked list is implemented.
  • Vector: A heritage class that is synchronised and resembles ArrayList.

Here is an example demonstrating ArrayList functionality:

import java.util.ArrayList;
import java.util.List; // Import List interface
public class ArList {
    public static void main(String[] args) {
        List<Object> ex = new ArrayList<>(); // Declaring ex as List<Object>
        ex.add(10); // int
        ex.add(10000000000000000L); // long (note: 'l' changed to 'L' for clarity)
        ex.add(10.12F); // float (note: 'f' changed to 'F' for clarity)
        ex.add("Hai"); // String
        ex.add("A"); // char represented as String
        ex.add(true); // boolean
        System.out.println(ex);
        System.out.println("Size of the list: " + ex.size());
    }
}

Output:

[10, 10000000000000000, 10.12, Hai, A, true]
Size of the list: 6

This example demonstrates that an ArrayList can hold dissimilar data types (due to <Object> generic type) and dynamically allocates memory, unlike fixed-size arrays.

The Set Interface

Collection is extended by the Set interface, which also defines a collection that forbids duplicate elements. By default, sets do not maintain elements by index and are unordered.

Typical ways that Set is implemented include:

  1. HashSet: Provides quick lookups by using a hash table for storing.
  2. LinkedHashSet: Keeps elements in their insertion order while extending HashSet.
  3. TreeSet: A set stored in a tree structure can be implemented using TreeSet, which automatically sorts its items in ascending order.

Here is an example demonstrating Set functionality to store unique elements:

import java.util.HashSet;
import java.util.Set;
public class SetExample {
    public static void main(String[] args) {
        System.out.println("Set example .....");
        Set<String> set = new HashSet<>();
        set.add("1");
        set.add("2");
        set.add("3");
        set.add("4");
        set.add("1"); // Duplicate, will not be added
        set.add("2"); // Duplicate, will not be added
        set.add("5");
        for (String temp : set) {
            System.out.println(temp);
        }
        System.out.println("Size of the set: " + set.size());
    }
}

Output: (Order may vary due to HashSet not guaranteeing order)

Set example .....
3
2
1
5
4
Size of the set: 5

Even though “1” and “2” were inserted more than once, as can be seen in the output, the Set only includes their distinct occurrences, making it five items in size rather than seven.

The Map Interface

The Map interface is essential for keeping track of key-value pairs. Importantly, each key must map to a maximum of one value and must be unique. Due to its lack of direct implementation of the Collection interface, Map is not precisely a Collection. However, the Collections Framework completely integrates maps, and you may use entrySet(), keySet(), or values() to access collection-views of a map’s entries, keys, or values.

Map is frequently implemented like follows:

  • HashMap: This method efficiently stores and retrieves key-values by using a hash table.
  • TreeMap: Key-value pairs are stored in a tree structure using a TreeMap, which keeps keys in ascending order.
  • Hashtable: Synced Hashtable is a heritage class that is comparable to HashMap.

Here is an example demonstrating Map functionality:

import java.util.HashMap;
import java.util.Map;
public class CollectionsDemo {
    public static void main(String[] args) {
        Map<String, String> m1 = new HashMap<>(); // Using generics for type safety
        m1.put("Zara", "8");
        m1.put("Mahnaz", "31");
        m1.put("Ayan", "12");
        m1.put("Daisy", "14");
        m1.put("Zara", "9"); // Key "Zara" already exists, value will be updated
        System.out.println(m1);
        System.out.println("Zara's value: " + m1.get("Zara"));
        System.out.println("Does Map contain key 'Ayan'? " + m1.containsKey("Ayan"));
        System.out.println("Size of the map: " + m1.size());
    }
}

Output: (Order may vary for HashMap)

{Zara=9, Ayan=12, Daisy=14, Mahnaz=31}
Zara's value: 9
Does Map contain key 'Ayan'? true
Size of the map: 4

Map contains unique keys (e.g., “Zara” is updated, not duplicated) mapped to values, as seen by this example. Basic functions like put(), get(), and containsKey() are also displayed.

An essential component of Java development, the Java Collections Framework offers a strong, adaptable, and type-safe set of tools for managing collections of objects.

Index