The Java Collections Framework is a set of interfaces and classes that support the manipulation of groups of objects. This tutorial provides an overview of the framework, including common interfaces and classes.
Overview
The Java Collections Framework consists of several key components:
- Interfaces: These define the structure and functionality of collections.
- Classes: These implement the interfaces and provide concrete implementations of the collections.
- ** Algorithms**: These are provided by the framework for operations on collections, such as searching and sorting.
Key Interfaces
Collection
: The root interface of the framework, representing a group of objects.List
: An ordered collection that allows duplicate elements.Set
: A collection that contains no duplicate elements.Queue
: A collection used to hold elements prior to processing.
Key Classes
ArrayList
: An implementation of theList
interface that uses an array to store elements.LinkedList
: An implementation of theList
interface that uses a doubly-linked list to store elements.HashSet
: An implementation of theSet
interface that uses a hash table to store elements.TreeSet
: An implementation of theSet
interface that stores elements in a sorted order.
Common Operations
The Java Collections Framework provides a rich set of methods for working with collections. Some common operations include:
- Adding elements:
add()
,addAll()
- Removing elements:
remove()
,removeAll()
- Checking for the presence of an element:
contains()
- Iterating over elements:
forEach()
,iterator()
Example
Here's a simple example of using an ArrayList
to store a list of strings:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
for (String fruit : list) {
System.out.println(fruit);
}
}
}
Further Reading
For more information on the Java Collections Framework, check out the official documentation.