3. Collection hierarchy in java ( Part 2: Classes )

Collection hierarchy in java.

Collection hierarchy in java
Collection hierarchy in java

The Java Collections Framework provides a rich set of classes that form a hierarchy for organizing and manipulating collections of objects. Here are the key classes in the collection hierarchy

ArrayList Class :

In Java, an ArrayList is a class that is part of the java.util package and provides a dynamic array-like data structure. It is a popular choice for storing and manipulating collections of objects. Unlike regular arrays, ArrayList automatically resizes itself as elements are added or removed.

Here are some key features and characteristics of ArrayList in Java:

  1. Dynamic Size: ArrayList can grow or shrink dynamically as elements are added or removed. You don’t need to specify the size of an ArrayList upfront, unlike regular arrays.
  2. Ordered Elements: ArrayList maintains the order of elements as they are added. The position of each element is determined by the order of insertion.
  3. Random Access: ArrayList provides efficient random access to elements using an index. You can retrieve or modify elements based on their index position.
  4. Generics: ArrayList supports the use of generics, allowing you to specify the type of objects it will store. This provides type safety and helps avoid runtime errors.
  5. Object Storage: ArrayList can store objects of any class or type, including primitive wrapper classes (e.g., Integer, Boolean) by autoboxing.
  6. Dynamic Operations: ArrayList provides various methods to add, remove, search, and manipulate elements. Some common methods include add(), remove(), get(), size(), contains(), and more.
  7. Auto-Expansion: When the ArrayList reaches its current capacity, it automatically expands itself by allocating more memory. This process is handled internally, and you don’t need to worry about managing the capacity manually.

Here’s an example of creating and using an ArrayList in Java:

import java.util.ArrayList;

public class Main{
    public static void main(String[] args) {
        // Creating an ArrayList of Strings
        ArrayList<String> fruits = new ArrayList<>();

        // Adding elements to the ArrayList
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Orange");

        // Accessing elements using index
        System.out.println(fruits.get(0));  // Output: "Apple"

        // Iterating over the ArrayList
        for (String fruit : fruits) {
            System.out.println(fruit);
        }

        // Removing an element
        fruits.remove("Banana");

        // Checking if an element exists
        System.out.println(fruits.contains("Orange"));  // Output: true

        // Size of the ArrayList
        System.out.println(fruits.size());  // Output: 2
    }
}

The ArrayList class in Java provides a variety of methods to manipulate and retrieve elements from the list. Here are some commonly used methods of ArrayList:

  1. add(E element): Adds the specified element to the end of the list.
  2. add(int index, E element): Inserts the specified element at the specified index in the list. Shifts the subsequent elements to the right.
  3. addAll(Collection<? extends E> c): Adds all the elements from the specified collection to the end of the list.
  4. addAll(int index, Collection<? extends E> c): Inserts all the elements from the specified collection into the list, starting at the specified index. Shifts the subsequent elements to the right.
  5. remove(Object obj): Removes the first occurrence of the specified element from the list, if present.
  6. remove(int index): Removes the element at the specified index from the list.
  7. clear(): Removes all elements from the list.
  8. get(int index): Returns the element at the specified index in the list.
  9. set(int index, E element): Replaces the element at the specified index in the list with the specified element.
  10. contains(Object obj): Returns true if the list contains the specified element; otherwise, returns false.
  11. isEmpty(): Returns true if the list is empty; otherwise, returns false.
  12. size(): Returns the number of elements in the list.
  13. indexOf(Object obj): Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
  14. lastIndexOf(Object obj): Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.
  15. subList(int fromIndex, int toIndex): Returns a new ArrayList containing elements from the specified fromIndex (inclusive) to the specified toIndex (exclusive).

These are just a few examples of the methods available in the ArrayList class. There are additional methods and utility methods you can explore in the Java documentation for the ArrayList class.

LinkedList Class :

In Java, the LinkedList class is another implementation of the List interface provided by the java.util package. It implements a doubly-linked list data structure, where each element is stored in a node that contains references to the previous and next nodes in the list.

Here are some key features and characteristics of the LinkedList class:

  1. Doubly-Linked Structure: Each element in a LinkedList is stored in a node that contains references to the previous and next nodes. This structure allows for efficient insertion and deletion of elements at both ends and in the middle of the list.
  2. Dynamic Size: Similar to ArrayList, LinkedList also dynamically resizes itself as elements are added or removed. You don’t need to specify the size of a LinkedList upfront.
  3. Sequential Access: LinkedList provides sequential access to elements, starting from the first or last node in the list. However, random access to elements by index is less efficient compared to ArrayList because it requires traversing the list from the beginning or end.
  4. No Random Access: Unlike ArrayList, LinkedList does not provide efficient random access to elements by index. Accessing an element at a specific index requires traversing the list from the beginning or end until reaching the desired position.
  5. Efficient Insertion and Deletion: LinkedList excels at insertion and deletion operations, especially at the beginning or end of the list. These operations involve updating references in the neighboring nodes, which is faster compared to shifting elements in an ArrayList.
  6. Additional Operations: LinkedList provides additional operations such as addFirst(), addLast(), removeFirst(), removeLast(), getFirst(), and getLast() to manipulate elements at the beginning or end of the list.
  7. Implements Deque Interface: LinkedList implements the Deque interface, which means it can be used as a double-ended queue, allowing efficient insertion and deletion at both ends.

Here’s an example of using the LinkedList class in Java:

import java.util.LinkedList;

public class Main{
    public static void main(String[] args) {
        // Creating a LinkedList of Strings
        LinkedList<String> colors = new LinkedList<>();

        // Adding elements to the LinkedList
        colors.add("Red");
        colors.add("Green");
        colors.add("Blue");

        // Accessing elements
        System.out.println(colors.getFirst());  // Output: "Red"
        System.out.println(colors.getLast());   // Output: "Blue"

        // Removing elements
        colors.removeFirst();
        colors.removeLast();

        // Adding elements at the beginning and end
        colors.addFirst("Yellow");
        colors.addLast("Purple");

        // Iterating over the LinkedList
        for (String color : colors) {
            System.out.println(color);
        }

        // Size of the LinkedList
        System.out.println(colors.size());  // Output: 2
    }
}

Here is a list of some commonly used methods provided by the LinkedList class in Java:

  1. add(E element): Adds the specified element to the end of the list.
  2. add(int index, E element): Inserts the specified element at the specified index in the list. Shifts the subsequent elements to the right.
  3. addAll(Collection<? extends E> c): Adds all the elements from the specified collection to the end of the list.
  4. addAll(int index, Collection<? extends E> c): Inserts all the elements from the specified collection into the list, starting at the specified index. Shifts the subsequent elements to the right.
  5. remove(Object obj): Removes the first occurrence of the specified element from the list, if present.
  6. remove(int index): Removes the element at the specified index from the list.
  7. clear(): Removes all elements from the list.
  8. get(int index): Returns the element at the specified index in the list.
  9. set(int index, E element): Replaces the element at the specified index in the list with the specified element.
  10. contains(Object obj): Returns true if the list contains the specified element; otherwise, returns false.
  11. isEmpty(): Returns true if the list is empty; otherwise, returns false.
  12. size(): Returns the number of elements in the list.
  13. indexOf(Object obj): Returns the index of the first occurrence of the specified element in the list, or -1 if the element is not found.
  14. lastIndexOf(Object obj): Returns the index of the last occurrence of the specified element in the list, or -1 if the element is not found.
  15. peek(): Retrieves, but does not remove, the first element of the list (equivalent to getFirst()).
  16. poll(): Retrieves and removes the first element of the list (equivalent to removeFirst()).
  17. offer(E element): Adds the specified element as the last element of the list (equivalent to addLast()).
  18. push(E element): Pushes an element onto the stack represented by the list (equivalent to addFirst()).
  19. pop(): Pops an element from the stack represented by the list (equivalent to removeFirst()).
  20. subList(int fromIndex, int toIndex): Returns a new LinkedList containing elements from the specified fromIndex (inclusive) to the specified toIndex (exclusive).

These are just a few examples of the methods available in the LinkedList class. There are additional methods and utility methods you can explore in the Java documentation for the LinkedList class.

Vector Class :

In Java, the Vector class is a legacy class that provides a dynamic array-like data structure. It is part of the java.util package and is similar to the ArrayList class. The Vector class was introduced in the early versions of Java and is synchronized, meaning it is thread-safe and can be used in concurrent environments.

Here are some key features and characteristics of the Vector class:

  1. Dynamic Size: Like ArrayList, Vector can dynamically resize itself as elements are added or removed. You don’t need to specify the size of a Vector upfront.
  2. Ordered Elements: Vector maintains the order of elements as they are added. The position of each element is determined by the order of insertion.
  3. Random Access: Vector provides efficient random access to elements using an index. You can retrieve or modify elements based on their index position.
  4. Synchronization: Unlike ArrayList, Vector is synchronized, which means it is thread-safe. Multiple threads can safely access and modify a Vector object concurrently without external synchronization.
  5. Legacy Class: The Vector class is considered a legacy class because it predates the collections framework introduced in Java 1.2. As a result, it lacks some of the newer features and enhancements available in the ArrayList and other collections classes.
  6. Enumeration Support: Vector provides enumeration support through the elements() method, allowing you to iterate over the elements of a Vector using an enumeration.
  7. Compatibility: Vector maintains compatibility with older Java code that relies on its specific features or behavior.

Despite being a legacy class, Vector can still be used in certain scenarios, such as when thread safety is a requirement or when working with older codebases that use Vector.

Here’s an example of using the Vector class in Java:

import java.util.Vector;

public class Main{
    public static void main(String[] args) {
        // Creating a Vector of Strings
        Vector<String> names = new Vector<>();

        // Adding elements to the Vector
        names.add("Alice");
        names.add("Bob");
        names.add("Charlie");

        // Accessing elements using index
        System.out.println(names.get(0));  // Output: "Alice"

        // Iterating over the Vector using enumeration
        Enumeration<String> enumeration = names.elements();
        while (enumeration.hasMoreElements()) {
            String name = enumeration.nextElement();
            System.out.println(name);
        }

        // Removing an element
        names.remove("Bob");

        // Checking if an element exists
        System.out.println(names.contains("Charlie"));  // Output: true

        // Size of the Vector
        System.out.println(names.size());  // Output: 2
    }
}

Here is a list of some commonly used methods provided by the Vector class in Java:

  1. add(E element): Adds the specified element to the end of the vector.
  2. add(int index, E element): Inserts the specified element at the specified index in the vector. Shifts the subsequent elements to the right.
  3. addAll(Collection<? extends E> c): Adds all the elements from the specified collection to the end of the vector.
  4. addAll(int index, Collection<? extends E> c): Inserts all the elements from the specified collection into the vector, starting at the specified index. Shifts the subsequent elements to the right.
  5. remove(Object obj): Removes the first occurrence of the specified element from the vector, if present.
  6. remove(int index): Removes the element at the specified index from the vector.
  7. clear(): Removes all elements from the vector.
  8. get(int index): Returns the element at the specified index in the vector.
  9. set(int index, E element): Replaces the element at the specified index in the vector with the specified element.
  10. contains(Object obj): Returns true if the vector contains the specified element; otherwise, returns false.
  11. isEmpty(): Returns true if the vector is empty; otherwise, returns false.
  12. size(): Returns the number of elements in the vector.
  13. indexOf(Object obj): Returns the index of the first occurrence of the specified element in the vector, or -1 if the element is not found.
  14. lastIndexOf(Object obj): Returns the index of the last occurrence of the specified element in the vector, or -1 if the element is not found.
  15. elements(): Returns an enumeration of the elements in the vector.
  16. subList(int fromIndex, int toIndex): Returns a new Vector containing elements from the specified fromIndex (inclusive) to the specified toIndex (exclusive).
  17. firstElement(): Returns the first element in the vector.
  18. lastElement(): Returns the last element in the vector.
  19. insertElementAt(E element, int index): Inserts the specified element at the specified index in the vector, shifting the subsequent elements to the right.
  20. removeElement(Object obj): Removes the first occurrence of the specified element from the vector, if present.
  21. removeElementAt(int index): Removes the element at the specified index from the vector.

These are just a few examples of the methods available in the Vector class. There are additional methods and utility methods you can explore in the Java documentation for the Vector class.

Ram Chadar

Hello! I'm Ram Chadar, a passionate software developer and freelancer based in Pune. Welcome to my blog, where I share my experiences, insights, and knowledge in the world of software development, different technologies, freelancing, and more.

View all posts by Ram Chadar →

One thought on “3. Collection hierarchy in java ( Part 2: Classes )

  1. I like the valuable info you provide in your articles. I’ll bookmark your blog and check again here regularly. I’m quite certain I’ll learn a lot of new stuff right here! Best of luck for the next!

Leave a Reply

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