Easy Tutorial
❮ Java Linkedlist Method Overloading ❯

Java Collections Framework

Before Java 2, Java provided ad-hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects.

Although these classes were useful, they lacked a central, unifying theme. As a result, the way to use the Vector class was significantly different from using the Properties class.

The Collections Framework was designed to meet several objectives:

-

The framework must be high-performance. The implementations of basic collections (dynamic arrays, linked lists, trees, hash tables) must be efficient.

-

The framework allows different types of collections to work in a similar manner and with high interoperability.

-

Extending and adapting a collection must be straightforward.

To this end, the entire collections framework is designed around a set of standard interfaces. You can use these interfaces' standard implementations directly, such as LinkedList, HashSet, and TreeSet, or you can implement your own collections through these interfaces.

From the Collections Framework diagram above, you can see that the Java Collections Framework mainly includes two types of containers: one is a Collection, which stores a collection of elements, and the other is a Map, which stores key/value pairs. The Collection interface has three subtypes: List, Set, and Queue. Below these are some abstract classes, and finally, concrete implementation classes, commonly used ones include ArrayList, LinkedList, HashSet, LinkedHashSet, HashMap, LinkedHashMap, and so on.

The Collections Framework is a unified architecture for representing and manipulating collections. All collections frameworks contain the following:

-** Abstract data types representing collections. For example, Collection, List, Set, Map, etc. Multiple interfaces are defined to manipulate collection objects in different ways.

Interfaces:

-

Implementations (classes): These are concrete implementations of the collection interfaces. Essentially, they are reusable data structures, such as ArrayList, LinkedList, HashSet, HashMap.

-

Algorithms: These are useful computations performed by methods in objects that implement collection interfaces, such as searching and sorting. These algorithms are polymorphic, as the same methods can be implemented differently on similar interfaces.

In addition to collections, the framework also defines several Map interfaces and classes. Maps store key/value pairs. Although Maps are not collections, they are fully integrated into collections.

Collections Framework Architecture

The Java Collections Framework provides a set of high-performance, easy-to-use interfaces and classes. The Java Collections Framework is located in the java.util package, so importing this package is necessary when using the Collections Framework.


Collection Interfaces

The Collections Framework defines several interfaces. This section provides an overview of each interface:

No. Interface Description
1 Collection Interface <br> Collection is the most basic collection interface. A Collection represents a group of Objects, the elements of the Collection. Java does not provide any classes that directly inherit from Collection, only sub-interfaces (such as List and Set). The Collection interface stores a group of non-unique, unordered objects.
2 List Interface <br> The List interface is an ordered Collection that allows precise control over where each element is inserted. Elements can be accessed by their index (their position in the List, similar to an array's subscript), with the first element having an index of 0, and duplicate elements are allowed. The List interface stores a group of non-unique, ordered (insertion order) objects.
3 Set <br> Set has the same interface as Collection but behaves differently; it does not store duplicate elements. The Set interface stores a group of unique, unordered objects.
4 SortedSet <br> Inherits from Set to store ordered collections.
5 Map <br> The Map interface stores a group of key-value objects, providing a mapping from keys to values.
6 Map.Entry <br> Describes an element (a key/value pair) in a Map. It is an internal interface of a Map.
7 SortedMap <br> Inherits from Map, keeping keys in ascending order.
8 Enumeration <br> This is a traditional interface and method definition for enumerating (obtaining one at a time) elements in a collection. This traditional interface has been replaced by the Iterator.

Differences Between Set and List

-

  1. The Set interface instance stores unordered, non-duplicate data. The List interface instance stores ordered, duplicate elements.

-

  1. Set retrieval efficiency is low, but deletion and insertion efficiency is high; insertion and deletion do not change the position of elements <Implemented by HashSet, TreeSet>.

-

  1. List is similar to an array but can grow dynamically, automatically adjusting its length based on the actual data stored. It offers high efficiency for element lookup but low efficiency for insertion and deletion, as these operations may shift other elements. <Implementing classes include ArrayList, LinkedList, Vector>.

Collection Implementing Classes (Collection Classes)

Java provides a set of standard collection classes that implement the Collection interface. Some of these are concrete classes that can be used directly, while others are abstract classes that provide partial implementations of the interface.

The standard collection classes are summarized in the following table:

No. Class Description
1 AbstractCollection <br>Implements most of the collection interface.
2 AbstractList <br>Inherits from AbstractCollection and implements most of the List interface.
3 AbstractSequentialList <br>Inherits from AbstractList and provides sequential rather than random access to data elements.
4 LinkedList <br>This class implements the List interface, allowing null elements. It is primarily used to create linked list data structures. It does not have synchronized methods, so if multiple threads access a List concurrently, they must be synchronized externally. For example: List list = Collections.synchronizedList(new LinkedList(...)); LinkedList has low lookup efficiency.
5 ArrayList <br>This class also implements the List interface, providing a dynamically resizable array. It offers better performance for random access and iterating over elements. It is not synchronized, so it should not be used in a multithreaded environment. ArrayList increases its current length by 50% when resizing, and has low efficiency for insertion and deletion.
6 AbstractSet <br>Inherits from AbstractCollection and implements most of the Set interface.
7 HashSet <br>This class implements the Set interface, does not allow duplicate elements, does not guarantee the order of elements, and allows at most one null element.
8 LinkedHashSet <br>A hash table and linked list implementation of the Set interface with predictable iteration order.
9 TreeSet <br>This class implements the Set interface and provides sorting capabilities.
10 AbstractMap <br>Implements most of the Map interface.
11 HashMap <br>HashMap is a hash table that stores key-value pairs. <br>This class implements the Map interface, storing data based on the hash code of the key, providing fast access speeds, allowing at most one null key, and does not support thread synchronization.
12 TreeMap <br>Inherits from AbstractMap and uses a tree structure.
13 WeakHashMap <br>Inherits from AbstractMap and uses a hash table with weak keys.
14 LinkedHashMap <br>Inherits from HashMap and sorts elements according to their natural order.
15 IdentityHashMap <br>Inherits from AbstractMap and uses reference equality when comparing keys.

In previous tutorials, we have discussed classes defined in the java.util package, as follows:

No. Class Description
1 Vector <br>This class is very similar to ArrayList but is synchronized and can be used in a multithreaded environment. It allows setting a default growth length, with the default expansion method being twice the original size.
2 Stack <br>Stack is a subclass of Vector that implements a standard last-in, first-out stack.
3 Dictionary <br>Dictionary is an abstract class used to store key/value pairs, similar in function to the Map class.
4 Hashtable <br>Hashtable is a subclass of Dictionary and is located in the java.util package.
5 Properties <br>Properties inherits from Hashtable and represents a persistent set of properties. Each key and its corresponding value in the property list is a string.
6 BitSet <br>The BitSet class creates a special type of array that holds bit values. The size of the BitSet array increases as needed.

Collection Algorithms

The collection framework defines several algorithms that can be used with collections and maps. These algorithms are defined as static methods in the collection classes. When trying to compare incompatible types, some methods can throw a ClassCastException. When attempting to modify an unmodifiable collection, an UnsupportedOperationException is thrown.

Collections define three static variables: EMPTY_SET, EMPTY_LIST, and EMPTY_MAP. These variables are all immutable.

Number Algorithm Description
1 Collection Algorithms <br>Here is a list of all algorithm implementations.

How to Use Iterators

Typically, you will want to traverse the elements of a collection. For example, displaying each element in the collection.

Traversing arrays is usually done using for loops or enhanced for loops, which can also be used in the collection framework. However, there is another method that uses iterators to traverse the collection framework. It is an object that implements the Iterator interface or the ListIterator interface.

Iterators allow you to obtain or remove elements of a collection through looping. ListIterator extends Iterator to allow bidirectional traversal of a list and modification of elements.

Number Iterator Method Description
1 Using Java Iterator <br>Here are examples listing all methods provided by the Iterator and ListIterator interfaces.

Traversing an ArrayList

Example

import java.util.*;

public class Test{
 public static void main(String[] args) {
     List<String> list=new ArrayList<String>();
     list.add("Hello");
     list.add("World");
     list.add("HAHAHAHA");
     // First method: using For-Each to traverse the List
     for (String str : list) {            // You can also rewrite this as for(int i=0;i&lt;list.size();i++)
        System.out.println(str);
     }

     // Second method: converting the list to an array and traversing
     String[] strArray=new String[list.size()];
     list.toArray(strArray);
     for(int i=0;i&lt;strArray.length;i++) // Here you can also rewrite this as for(String str:strArray)
     {
        System.out.println(strArray[i]);
     }

    // Third method: using an iterator for traversal

     Iterator<String> ite=list.iterator();
     while(ite.hasNext())// Check if there is a next value
     {
         System.out.println(ite.next());
     }
 }
}

Analysis:

All three methods are used to traverse the ArrayList collection. The third method uses an iterator, which does not need to worry about exceeding the length of the collection during traversal.

Traversing a Map

Example

import java.util.*;

public class Test{
     public static void main(String[] args) {
      Map&lt;String, String> map = new HashMap&lt;String, String>();
      map.put("1", "value1");
      map.put("2", "value2");
      map.put("3", "value3");

      // First method: commonly used, double key retrieval
      System.out.println("Traversing key and value through Map.keySet:");
      for (String key : map.keySet()) {
       System.out.println("key= "+ key + " and value= " + map.get(key));
      }

      // Second method
      System.out.println("Traversing key and value through Map.entrySet using iterator:");
Iterator&lt;Map.Entry&lt;String, String>> it = map.entrySet().iterator();
while (it.hasNext()) {
    Map.Entry&lt;String, String> entry = it.next();
    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

// Third method: Recommended, especially for large capacities
System.out.println("Iterating over keys and values using Map.entrySet");
for (Map.Entry&lt;String, String> entry : map.entrySet()) {
    System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
}

// Fourth method
System.out.println("Iterating over all values using Map.values(), but cannot iterate over keys");
for (String v : map.values()) {
    System.out.println("value= " + v);
}
}

How to Use Comparators

TreeSet and TreeMap store elements in a sorted order. However, this is precisely defined by a comparator.

This interface allows us to sort a collection in different ways.

Number Comparator Method Description
1 Using Java Comparator <br>Here, all methods provided by the Comparator interface are listed through examples

Summary

The Java Collections Framework provides programmers with prepackaged data structures and algorithms to manipulate them.

A collection is an object that can hold references to other objects. The collection interface declares the operations that can be performed on each type of collection.

The classes and interfaces of the collections framework are in the java.util package.

Any object added to a collection class is automatically converted to the Object type, so it needs to be cast back to its original type when retrieved.

❮ Java Linkedlist Method Overloading ❯