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:
- Dynamic Size:
ArrayList
can grow or shrink dynamically as elements are added or removed. You don’t need to specify the size of anArrayList
upfront, unlike regular arrays. - Ordered Elements:
ArrayList
maintains the order of elements as they are added. The position of each element is determined by the order of insertion. - Random Access:
ArrayList
provides efficient random access to elements using an index. You can retrieve or modify elements based on their index position. - 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. - Object Storage:
ArrayList
can store objects of any class or type, including primitive wrapper classes (e.g., Integer, Boolean) by autoboxing. - Dynamic Operations:
ArrayList
provides various methods to add, remove, search, and manipulate elements. Some common methods includeadd()
,remove()
,get()
,size()
,contains()
, and more. - 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
:
add(E element)
: Adds the specified element to the end of the list.add(int index, E element)
: Inserts the specified element at the specified index in the list. Shifts the subsequent elements to the right.addAll(Collection<? extends E> c)
: Adds all the elements from the specified collection to the end of the list.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.remove(Object obj)
: Removes the first occurrence of the specified element from the list, if present.remove(int index)
: Removes the element at the specified index from the list.clear()
: Removes all elements from the list.get(int index)
: Returns the element at the specified index in the list.set(int index, E element)
: Replaces the element at the specified index in the list with the specified element.contains(Object obj)
: Returnstrue
if the list contains the specified element; otherwise, returnsfalse
.isEmpty()
: Returnstrue
if the list is empty; otherwise, returnsfalse
.size()
: Returns the number of elements in the list.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.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.subList(int fromIndex, int toIndex)
: Returns a newArrayList
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:
- 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. - 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 aLinkedList
upfront. - 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 toArrayList
because it requires traversing the list from the beginning or end. - 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. - 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 anArrayList
. - Additional Operations:
LinkedList
provides additional operations such asaddFirst()
,addLast()
,removeFirst()
,removeLast()
,getFirst()
, andgetLast()
to manipulate elements at the beginning or end of the list. - Implements
Deque
Interface:LinkedList
implements theDeque
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:
add(E element)
: Adds the specified element to the end of the list.add(int index, E element)
: Inserts the specified element at the specified index in the list. Shifts the subsequent elements to the right.addAll(Collection<? extends E> c)
: Adds all the elements from the specified collection to the end of the list.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.remove(Object obj)
: Removes the first occurrence of the specified element from the list, if present.remove(int index)
: Removes the element at the specified index from the list.clear()
: Removes all elements from the list.get(int index)
: Returns the element at the specified index in the list.set(int index, E element)
: Replaces the element at the specified index in the list with the specified element.contains(Object obj)
: Returnstrue
if the list contains the specified element; otherwise, returnsfalse
.isEmpty()
: Returnstrue
if the list is empty; otherwise, returnsfalse
.size()
: Returns the number of elements in the list.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.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.peek()
: Retrieves, but does not remove, the first element of the list (equivalent togetFirst()
).poll()
: Retrieves and removes the first element of the list (equivalent toremoveFirst()
).offer(E element)
: Adds the specified element as the last element of the list (equivalent toaddLast()
).push(E element)
: Pushes an element onto the stack represented by the list (equivalent toaddFirst()
).pop()
: Pops an element from the stack represented by the list (equivalent toremoveFirst()
).subList(int fromIndex, int toIndex)
: Returns a newLinkedList
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:
- Dynamic Size: Like
ArrayList
,Vector
can dynamically resize itself as elements are added or removed. You don’t need to specify the size of aVector
upfront. - Ordered Elements:
Vector
maintains the order of elements as they are added. The position of each element is determined by the order of insertion. - Random Access:
Vector
provides efficient random access to elements using an index. You can retrieve or modify elements based on their index position. - Synchronization: Unlike
ArrayList
,Vector
is synchronized, which means it is thread-safe. Multiple threads can safely access and modify aVector
object concurrently without external synchronization. - 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 theArrayList
and other collections classes. - Enumeration Support:
Vector
provides enumeration support through theelements()
method, allowing you to iterate over the elements of aVector
using an enumeration. - 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:
add(E element)
: Adds the specified element to the end of the vector.add(int index, E element)
: Inserts the specified element at the specified index in the vector. Shifts the subsequent elements to the right.addAll(Collection<? extends E> c)
: Adds all the elements from the specified collection to the end of the vector.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.remove(Object obj)
: Removes the first occurrence of the specified element from the vector, if present.remove(int index)
: Removes the element at the specified index from the vector.clear()
: Removes all elements from the vector.get(int index)
: Returns the element at the specified index in the vector.set(int index, E element)
: Replaces the element at the specified index in the vector with the specified element.contains(Object obj)
: Returnstrue
if the vector contains the specified element; otherwise, returnsfalse
.isEmpty()
: Returnstrue
if the vector is empty; otherwise, returnsfalse
.size()
: Returns the number of elements in the vector.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.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.elements()
: Returns an enumeration of the elements in the vector.subList(int fromIndex, int toIndex)
: Returns a newVector
containing elements from the specified fromIndex (inclusive) to the specified toIndex (exclusive).firstElement()
: Returns the first element in the vector.lastElement()
: Returns the last element in the vector.insertElementAt(E element, int index)
: Inserts the specified element at the specified index in the vector, shifting the subsequent elements to the right.removeElement(Object obj)
: Removes the first occurrence of the specified element from the vector, if present.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.
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!