Collection framework
Collection framework
Collection)-
- Interface: Collection<E>
- Methods: add(E e), remove(E e), contains(Object o), size(), iterator(), etc.
The Iterator interface in Java - is a key component of the Collection Framework. It allows
you to iterate over a collection of objects, such as a list, set, or map, and access each element in a
standardized way.
Here's a breakdown of the Iterator interface:
- Methods:
- hasNext(): Returns true if there are more elements to iterate.
- next(): Returns the next element in the collection.
- remove(): Removes the last element returned by next().
- How it works:
1. Create an iterator object from a collection (e.g., Iterator<String> iterator = list.iterator();).
2. Use hasNext() to check if there are more elements.
3. Use next() to retrieve the next element.
4. Use remove() to remove the last element (optional).
- Benefits:
- Allows for generic iteration over different collection types.
- Provides a standardized way of accessing elements.
- Enables the use of polymorphism and abstraction.
- Example:
apple
banana
cherry
Collection interface in Java - is the root interface of the Collection Framework hierarchy. It
defines the basic methods that all collection classes must implement.
The Collection interface extends the Iterable interface, which means that all collections can be iterated
over using a foreach loop or an Iterator.
** the Collection interface is a generic interface, meaning it can work with any type of object. This
allows for type safety and flexibility in the Collection Framework.
List interface in Java- is a part of the Collection Framework and extends the Collection
interface. It defines a collection that maintains a specific order of elements, allowing for indexing and
positional access.
Types of Lists:
1. ArrayList: A resizable array implementation.
2. LinkedList: A linked list implementation.
3. Vector: A legacy implementation (similar to ArrayList).
Example:
** the List interface is a generic interface, allowing for type safety and flexibility.
ArrayList- is a specific implementation of the List interface in Java, which provides a resizable array
data structure. It's a popular choice for most use cases where a list is needed.
LinkedList - is a data structure in which elements are stored in nodes that are linked together
through pointers. Each node in the list contains a reference (or "link") to the next node in the list.
In Java, the LinkedList class is a implementation of the List interface, which provides a linked list data
structure.
- Implementation: LinkedList uses a doubly-linked list data structure, where each node has a reference
to the previous and next node.
- Insertion and deletion: LinkedList provides efficient insertion and deletion operations, as only the
affected nodes need to be updated.
- Performance: LinkedList provides linear-time performance for most operations, making it suitable for
applications where frequent insertions and deletions are necessary.
- Memory usage: LinkedList uses more memory than ArrayList, as each node requires additional memory
for the references.
- Frequent insertions and deletions: LinkedList is suitable when the list is frequently modified.
- Implementing queues or stacks: LinkedList can be used to implement data structures like queues or
stacks.
- Memory-efficient implementation: LinkedList can be more memory-efficient than ArrayList when the
list is sparse or has frequent insertions and deletions.
- java.util.Collection (interface)
- java.util.List (interface)
- java.util.ArrayList (class)
- java.util.LinkedList (class)
- java.util.Vector (class)
benefits of using LinkedList in the Java Collection Framework include:
Vector- is a legacy class that implements the List interface. It is similar to ArrayList, but with some key
differences:
Stack- is a data structure that follows the Last-In-First-Out (LIFO) principle, meaning the last element
added to the stack is the first one to be removed. In Java, the Stack class is a legacy class that extends
the Vector class and implements the last-in-first-out (LIFO) data structure.
The Stack class is a legacy class and is not part of the Java Collection Framework. It is largely replaced by
the ArrayDeque class, which provides a more efficient and modern implementation of a stack.
*** the Stack class is a legacy class and is not commonly used in new code. Instead, the ArrayDeque
class is recommended for implementing a stack data structure.
Queue interface in Java - is a part of the Java Collection Framework and provides a First-In-
First-Out (FIFO) data structure. It is a generic interface that allows for insertion, removal, and inspection
of elements.
- Job scheduling
- Print queues
- Network protocols
- Thread pools
*** the Queue interface is a generic interface, allowing for type safety and flexibility.
The Set interface in Java- is a part of the Java Collection Framework and provides a collection
that contains no duplicate elements. It is a generic interface that allows for the storage and retrieval of
elements.
** sets are unordered collections, meaning that the order of the elements is not preserved. If you need
to preserve the order, you can use a List or a LinkedHashSet.
HashSet- is a class in Java that implements the Set interface and uses a hash table for storage. It is a
generic class, meaning it can store elements of any type.
- Hash-based storage: HashSet uses a hash table to store elements, which provides fast lookup,
insertion, and removal operations.
- No duplicates: HashSet does not allow duplicate elements.
- Unordered: HashSet does not preserve the order of elements.
- Null elements: HashSet allows null elements.
- Performance: HashSet provides constant-time performance for basic operations like add, remove, and
contains.
**HashSet is not thread-safe, meaning it is not suitable for use in multithreaded environments without
additional synchronization. If you need a thread-safe set, you can use a ConcurrentHashSet or a
CopyOnWriteArraySet.
LinkedHashSet - is a class in Java that implements the Set interface and extends the HashSet
class. It is a generic class, meaning it can store elements of any type.
**LinkedHashSet is not thread-safe, meaning it is not suitable for use in multithreaded environments
without additional synchronization. If you need a thread-safe set, you can use a ConcurrentHashSet or a
CopyOnWriteArraySet.
SortedSet interface in Java- is a part of the Java Collection Framework and extends the Set
interface. It is a generic interface that provides a sorted collection of elements.
- Sorted elements: Elements are sorted according to their natural ordering or a specified Comparator.
- No duplicates: SortedSet does not allow duplicate elements.
- Ordered iteration: Elements are iterated in sorted order.
** SortedSet is not thread-safe, meaning it is not suitable for use in multithreaded environments
without additional synchronization. If you need a thread-safe sorted set, you can use a
ConcurrentSkipListSet.
TreeSet - is a class in Java that implements the SortedSet interface and uses a tree data structure to
store elements. It is a generic class, meaning it can store elements of any type.
- Tree-based storage: TreeSet uses a self-balancing binary search tree to store elements, which provides
efficient sorting and searching capabilities.
- Sorted elements: Elements are sorted according to their natural ordering or a specified Comparator.
- No duplicates: TreeSet does not allow duplicate elements.
- Ordered iteration: Elements are iterated in sorted order.
- Efficient operations: TreeSet provides efficient operations for adding, removing, and searching
elements, with a time complexity of O(log n).
**TreeSet is not thread-safe, meaning it is not suitable for use in multithreaded environments without
additional synchronization. If you need a thread-safe sorted set, you can use a ConcurrentSkipListSet.
Map interface in Java - is a part of the Java Collection Framework and provides a data structure
for storing and retrieving elements based on a key.
example -
**Map interface is a generic interface, allowing for type safety and flexibility.
**Map is not a Collection, but rather a separate data structure that provides additional functionality.
HashMap - is a class in Java that implements the Map interface and uses a hash table for storage. It
is a generic class, meaning it can store key-value pairs of any type.
**HashMap is not thread-safe, meaning it is not suitable for use in multithreaded environments without
additional synchronization. If you need a thread-safe map, you can use a ConcurrentHashMap.
LinkedHashMap- is a class in Java that extends the HashMap class and implements the Map
interface. It is a generic class, meaning it can store key-value pairs of any type.
example
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("apple", 5);
System.out.println(map.get("apple")); // Output: 5
**LinkedHashMap is not thread-safe, meaning it is not suitable for use in multithreaded environments
without additional synchronization. If you need a thread-safe map, you can use a ConcurrentHashMap.
TreeMapclass- is a class in Java that implements the Map interface and uses a tree data structure
to store elements. It is a generic class, meaning it can store key-value pairs of any type.
example
TreeMap<String, Integer> map = new TreeMap<>();
map.put("apple", 5);
System.out.println(map.get("apple")); // Output: 5
** TreeMap is not thread-safe, meaning it is not suitable for use in multithreaded environments without
additional synchronization. If you need a thread-safe sorted map, you can use a ConcurrentSkipListMap.
**Difference between treeSet & TreeMap-
-TreeSet and TreeMap are both implementations of the SortedSet and SortedMap interfaces,
respectively.
- TreeSet is a sorted set of unique elements, while TreeMap is a sorted map of key-value pairs.
- TreeSet does not allow null elements, while TreeMap allows null values.
- TreeSet does not maintain a mapping between elements, while TreeMap maps keys to values.
TreeSet
set.add("apple");
set.add("banana");
TreeMap
map.put("apple", 5);
map.put("banana", 10);
In this example, the TreeSet stores a sorted set of unique strings, while the TreeMap stores a sorted
map of strings to integers.
hash table class - is a data structure that implements the Map interface using a hash table data
structure.
Features of a hash table class:
- Hash-based storage: Elements are stored in an array using a hash function to map keys to indices.
- Key-value pairs: Hash tables store elements as key-value pairs.
- Fast lookup and insertion: Hash tables provide fast lookup, insertion, and removal operations (average
time complexity of O(1)).
- Collision handling: Hash tables use techniques like chaining or open addressing to handle collisions
(when two keys hash to the same index).
example
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 5);
System.out.println(map.get("apple")); // Output: 5
The Comparable interface -in Java is used to order the objects of a class. It is used to
compare the objects of the same class.
- compareTo(Object obj): This method compares the current object with the specified object and returns
an integer.
- Negative integer: if the current object is less than the specified object.
- Zero: if the current object is equal to the specified object.
- Positive integer: if the current object is greater than the specified object.
example
In this example, the Student class implements the Comparable interface and overrides the compareTo
method to compare students based on their roll numbers.
The Comparable interface is used in various data structures and algorithms, such as sorting, searching,
and priority queues.
Comparator interface in Java- is used to compare objects of a class. It is used to order the
objects of a class that implements the Comparable interface.
The Comparator interface has two methods:
- compare(Object obj1, Object obj2): This method compares the two specified objects and returns an
integer.
- equals(Object obj): This method checks if the specified object is equal to the comparator.
example
public class StudentComparator implements Comparator<Student> {
public int compare(Student s1, Student s2) {
return s1.getRollNumber() - s2.getRollNumber();
}
}
In this example, the StudentComparator class implements the Comparator interface and overrides the
compare method to compare students based on their roll numbers.
The Comparator interface is used in various data structures and algorithms, such as sorting, searching,
and priority queues.
**The Comparable and Comparator interfaces in Java are both used for comparing objects, but they
have some key differences:
Comparable Interface:
- Implemented by the class whose objects are to be compared
- Defines a natural ordering of objects
- Only one comparison logic can be defined
- compareTO() method is used for comparison
Comparator Interface:
- Implemented by a separate class that compares objects
- Defines a custom ordering of objects
- Multiple comparison logics can be defined
- compare() method is used for comparison
Key Features:
- Persistent: The Properties class can save and load data from a stream .
- String key-value pairs: Each key and its corresponding value in the property list is a string .
- Default values: A property list can contain another property list as its "defaults"; this second property
list is searched if the property key is not found in the original property list .
- Thread-safe: Multiple threads can share a single Properties object without the need for external
synchronization .
- getProperty(String key): Searches for the property with the specified key in this property list .
- setProperty(String key, String value): Calls the Hashtable method put .
- load(Reader reader): Reads a property list (key and element pairs) from the input character stream .
- store(Writer writer, String comments): Writes this property list (key and element pairs) in this
Properties table to the output character stream .
Advantages:
- Easy to use: The Properties class provides methods to get data from the properties file and store data
into the properties file .
- Flexible: It can be used to get the properties of a system .
- Maintainable: No maintenance problem, as you don't need to recompile the Java class if you change
the value of the properties file .
example
import java.util.Properties;
// Set properties
props.setProperty("name", "John");
props.setProperty("age", "30");
// Get properties
String name = props.getProperty("name");
String age = props.getProperty("age");