Introduction to Java Collections
What Are Collections?
In Java, a Collection is a framework that provides an architecture to store and manipulate a group of objects. It includes various interfaces and classes that help in managing collections of data effectively.
Important: Collections in Java are part of the
java.util
package.Why Use Collections?
- Dynamic size: Collections can grow and shrink as needed.
- Data Manipulation: Collections provide various methods for searching, sorting, and manipulating data.
- Ease of Use: High-level methods simplify common tasks like adding, removing, and iterating through elements.
Types of Collections
- List: An ordered collection that allows duplicate elements. Example:
ArrayList
,LinkedList
. - Set: A collection that does not allow duplicate elements. Example:
HashSet
,TreeSet
. - Map: A collection of key-value pairs, where keys are unique. Example:
HashMap
,TreeMap
.
Collection Interfaces
Java Collections framework comprises several interfaces:
- Collection: The root interface for the collection hierarchy.
- List: Extends Collection and represents an ordered collection.
- Set: Extends Collection and represents a collection that cannot contain duplicates.
- Map: Represents a collection of key-value pairs.
Example of using a List
:
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) {
List fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
for (String fruit : fruits) {
System.out.println(fruit);
}
}
}
Best Practices
- Use interfaces (like
List
,Set
,Map
) rather than implementation classes for variable declaration. - Choose the right implementation based on your use case (e.g., use
ArrayList
for fast access,LinkedList
for frequent insertions). - Be cautious with null values in collections.
FAQ
What is the difference between ArrayList
and LinkedList
?
ArrayList
is backed by a dynamic array and is better for random access, whereas LinkedList
is better for frequent insertions and deletions.
Can a Set
contain duplicates?
No, a Set
does not allow duplicate elements. If you try to add a duplicate, it will be ignored.
What is a Map
?
A Map
is a collection of key-value pairs where each key is unique, and each key maps to exactly one value.