Collections in Java: ArrayList, HashSet, and HashMap


Introduction to Java Collections

Collections in Java provide a convenient way to store, manage, and manipulate groups of objects. They are a fundamental part of the Java Collections Framework and offer a wide range of data structures to suit different needs. In this guide, we'll explore three commonly used collection types: ArrayList, HashSet, and HashMap.


ArrayList

ArrayList is a dynamic array that can grow or shrink as needed. It allows you to store and manage a list of objects. Here's an example of using an ArrayList to store a list of strings:


import java.util.ArrayList;
import java.util.List;
public class ArrayListExample {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
names.add("Charlie");

System.out.println(names); // [Alice, Bob, Charlie]
}
}

HashSet

HashSet is an implementation of the Set interface that stores unique elements. It does not allow duplicates. Here's an example of using a HashSet to store a set of integers:


import java.util.HashSet;
import java.util.Set;
public class HashSetExample {
public static void main(String[] args) {
Set<Integer> numbers = new HashSet<>();
numbers.add(1);
numbers.add(2);
numbers.add(1); // Duplicate, not added

System.out.println(numbers); // [1, 2]
}
}

HashMap

HashMap is an implementation of the Map interface that stores key-value pairs. It allows you to map keys to values and retrieve values based on their keys. Here's an example of using a HashMap to store key-value pairs:


import java.util.HashMap;
import java.util.Map;
public class HashMapExample {
public static void main(String[] args) {
Map<String, Integer> ages = new HashMap<>();
ages.put("Alice", 25);
ages.put("Bob", 30);

System.out.println(ages.get("Alice")); // 25
}
}

Conclusion

Collections are an integral part of Java, offering versatile data structures for storing and manipulating data. You've learned about ArrayList, HashSet, and HashMap in this guide. As you continue your Java development journey, understanding and effectively using collections will be crucial for working with data in your applications.