Collections in Java

Collections in Java

In Java, the java.util package provides a variety of collection classes and interfaces that allows us to store, manipulate, and organize groups of objects.Collections are a fundamental part of Java programming, and they provide a way to work with data in a structured manner.

Here are some of the key collection classes and interfaces in Java:

List: Lists are ordered collections that allow duplicate elements. Some commonly used List implementations are:

ArrayList: Resizable array implementation of List.

LinkedList: Doubly linked list implementation of List.

Vector: A synchronized version of ArrayList (not commonly used nowadays).

Set: Sets are collections that do not allow duplicate elements. Some commonly used Set implementations are:

HashSet: Unordered, using a hash table for storage.

LinkedHashSet: Ordered, using a hash table with a linked list for storage.

TreeSet: Ordered, using a Red-Black tree for storage.

Map: Maps are collections of key-value pairs. Each key is associated with a value, and keys are unique. Some commonly used Map implementations are:

HashMap: Unordered, using a hash table for storage.

LinkedHashMap: Ordered, using a hash table with a linked list for storage.

TreeMap: Ordered, using a Red-Black tree for storage.

Queue: Queues represent a collection designed for holding elements prior to processing. Commonly used implementations are:

LinkedList: Can be used as a queue implementation.

PriorityQueue: Implements a priority queue.

Deque: A double-ended queue that allows insertion and removal of elements from both ends. Commonly used implementations include LinkedList.

Collections: The Collections class provides utility methods for working with collections. For example, you can use methods like sort(), shuffle(), reverse(), and binarySearch() to perform various operations on collections.

Iterable and Iterator:

The Iterable interface allows us to create objects that can be iterated (looped) over. The Iterator interface provides a way to iterate through the elements of a collection sequentially.

Collection and Map Interfaces: These are the fundamental interfaces that various collection classes and map classes implement. For example, List, Set, and Map are interfaces.


Here's an example of how to use a List (specifically, ArrayList) in Java:

public class Main {
    public static void main(String[] args) {
        List<String> myList = new ArrayList<>();

        // Adding elements to the list
        myList.add("Apple");
        myList.add("Banana");
        myList.add("Cherry");

        // Accessing elements by index
        String fruit = myList.get(1); // Retrieves "Banana"

        // Iterating through the list
        for (String item : myList) {
            System.out.println(item);
        }
    }
}        

To view or add a comment, sign in

More articles by AlphaDot Technologies

Insights from the community

Others also viewed

Explore topics