What types of collections exist in Java?
sobes.tech AI
Answer from AI
In Java, the main collection types are represented in the J2SE Collections Framework and are divided into three main categories:
- Set:
- Unordered collections that do not contain duplicates.
- Implementations:
HashSet,LinkedHashSet,TreeSet.
- List:
- Ordered collections where elements are accessible by index. They can contain duplicates.
- Implementations:
ArrayList,LinkedList,Vector,Stack.
- Map:
- Store pairs of "key-value". Keys are unique, values are not. Elements are stored without a specific order (except
LinkedHashMapandTreeMap). - Implementations:
HashMap,LinkedHashMap,TreeMap,Hashtable.
- Store pairs of "key-value". Keys are unique, values are not. Elements are stored without a specific order (except
Besides these main interfaces (Set, List, Map), there are also less common ones:
- Queue: A collection designed to hold elements until they are processed. Usually operates on FIFO principle (first in, first out).
- Implementations:
PriorityQueue,ArrayDeque,LinkedList.
- Implementations:
- Deque: A double-ended queue supporting insertion and removal of elements from both ends.
- Implementations:
ArrayDeque,LinkedList.
- Implementations:
The abstract class Collection is the root interface for most of the collection hierarchy (Set, List, Queue). Map does not implement Collection.
Examples of usage:
// ArrayList
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Apple"); // Duplicate is allowed
// HashSet
HashSet<String> set = new HashSet<>();
set.add("Apple");
set.add("Banana");
set.add("Apple"); // Ignored, as duplicates are not allowed
// HashMap
HashMap<String, Integer> map = new HashMap<>();
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 1); // Values can be the same
Choosing a specific implementation depends on required characteristics: the need to preserve order, allowance of duplicates, access and insertion speed, multithreading, etc. For example, ArrayList is convenient for quick access by index, LinkedList for frequent insertions/deletions in the middle, HashSet for fast lookup of unique elements, and HashMap for storing data by key.
Vector and Hashtable are synchronized (thread-safe) implementations, but it is generally preferable to use unsynchronized versions (ArrayList, HashMap) and handle synchronization at another level, or use collections from the java.util.concurrent package. LinkedHashSet and LinkedHashMap preserve insertion order. TreeSet and TreeMap store elements in sorted order.
ArrayDeque is often preferred over Stack and LinkedList when used as a stack or queue due to better performance.
PriorityQueue organizes elements according to their natural order or with the help of a Comparator.