Collections
List
A List is an ordered collection of elements.
Elements can be accessed by their index.
Java provides several implementations of the List interface:
ArrayList: A resizable array that is backed by an array.
LinkedList: A doubly-linked list that allows for fast insertion and deletion at the beginning or end of the list.
Vector: Similar to ArrayList but is synchronized, which makes it thread-safe.
Example:
Set
A Set is an unordered collection of unique elements.
Java provides several implementations of the Set interface:
HashSet: Uses a hash table to store the elements, which provides constant time performance for basic operations.
TreeSet: Stores the elements in a sorted order, which provides faster searching.
LinkedHashSet: Maintains the insertion order of the elements, which provides predictable iteration order.
Example:
Map
A Map is a collection of key-value pairs.
Keys must be unique, but values can be duplicated.
Java provides several implementations of the Map interface:
HashMap: Uses a hash table to store the elements, which provides constant time performance for basic operations.
TreeMap: Stores the elements in a sorted order based on the keys.
LinkedHashMap: Maintains the insertion order of the elements, which provides predictable iteration order.
Example:
Queue
A Queue is a collection that represents a waiting line.
Elements are added to the end of the queue and removed from the front.
Java provides several implementations of the Queue interface:
LinkedList: A doubly-linked list that allows for fast insertion and deletion at the beginning or end of the list.
PriorityQueue: A queue that orders its elements according to their natural order or a specified comparator.
Example:
Stack
A Stack is a collection that represents a stack of items.
Elements are added to the top of the stack and removed from the top.
Java provides a Stack class that implements the Stack interface.
Example:
Collection utilities
Java provides several utility classes for working with collections:
Collections: Provides methods for sorting, searching, and manipulating collections.
Arrays: Provides methods for working with arrays, such as sorting and searching.
Example:
Last updated