In java, the term collection refers to a framework that provide an architecture to store and manipulate a group of objects. These collections
can be used to store, retrieve, manipulate and communicate aggregate data. The collection framework is part of the ‘java. util’ package and is a unified architecture for representing and manipulating collections.
There are key interfaces :
Collection Interface:
the root interface for the collection structure.
It is also an used sub interfaces . List, queue, set, deque.
List interfaces:
Ordered collection.
allows the duplicate elements.
common implementations. ‘Array list’, linked list , vector.
Set interface:
A collection that does not allow duplicate elements.
Common implementations, hash set, tree set.
Deque interface:
double ended queue that allows insertion and removal from both ends
common implementations array deque linkedlist
Queue interface:
designed for holding elements prior to processing
typically orders elements in a fifo.
import java.util.ArrayList; import java.util.List; public class ArrayListExample { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("Apple"); list.add("Banana"); list.add("Orange"); for (String fruit : list) { System.out.println(fruit); } } }
Characteristics of Collections
- Generic: Collections in java are generic they can hold objects of any type specified at runtime.
- Dynamic: Many collections classes can dynamically grow and shrink in size.
- Heterogeneous: Collections can store objects of different types, although using generics ensures type safety by allowing collections to be type specific.
- Utility Methods: The collections utility class provides static methods for common operationslike sorting, searching and synchronization.
import java.util.ArrayList; import java.util.List; public class CollectionExample { public static void main(String[] args) { // Create a list to store strings List<String> fruits = new ArrayList<>(); // Add elements to the list fruits.add("Apple"); fruits.add("Banana"); fruits.add("Cherry"); // Iterate over the list for (String fruit : fruits) { System.out.println(fruit); } } }