0% found this document useful (0 votes)
3 views

Collection framework

The document provides an overview of the Java Collection Framework, detailing the Collection interface and its various implementations including List, Set, Queue, and Map interfaces. It describes key classes such as ArrayList, LinkedList, HashSet, and their functionalities, as well as the Iterator interface for traversing collections. Additionally, it highlights the characteristics and use cases for each collection type, emphasizing the importance of generics for type safety.

Uploaded by

foxdevil484
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Collection framework

The document provides an overview of the Java Collection Framework, detailing the Collection interface and its various implementations including List, Set, Queue, and Map interfaces. It describes key classes such as ArrayList, LinkedList, HashSet, and their functionalities, as well as the Iterator interface for traversing collections. Additionally, it highlights the characteristics and use cases for each collection type, emphasizing the importance of generics for type safety.

Uploaded by

foxdevil484
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 17

Collection Interface (java.util.

Collection)-

- Interface: Collection<E>
- Methods: add(E e), remove(E e), contains(Object o), size(), iterator(), etc.

Collection Interface Hierarchy-


- Set Interface (java.util.Set): A collection without duplicates.
- HashSet: A set implementation using a hash table.
- LinkedHashSet: A set implementation using a linked hash table.
- TreeSet: A sorted set implementation using a tree.
- List Interface (java.util.List): A collection with indexing.
- ArrayList: A list implementation using an array.
- LinkedList: A list implementation using a linked list.
- Vector: A legacy list implementation.
- Queue Interface (java.util.Queue): A collection for First-In-First-Out (FIFO) order.
- ArrayDeque: A queue implementation using an array.
- LinkedList: A queue implementation using a linked list.
- Map Interface (java.util.Map): A collection of key-value pairs.
- HashMap: A map implementation using a hash table.
- LinkedHashMap: A map implementation using a linked hash table.
- TreeMap: A sorted map implementation using a tree.
Abstract Classes
- AbstractCollection: A skeletal implementation of the Collection interface.
- AbstractSet: A skeletal implementation of the Set interface.
- AbstractList: A skeletal implementation of the List interface.
- AbstractQueue: A skeletal implementation of the Queue interface.
- AbstractMap: A skeletal implementation of the Map interface.

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:

List<String> list = Arrays.asList("apple", "banana", "cherry");


Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

This will output:

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.

key methods defined in the Collection interface:

1. size(): Returns the number of elements in the collection.


2. isEmpty(): Returns true if the collection is empty.
3. contains(Object o): Returns true if the collection contains the specified element.
4. iterator(): Returns an Iterator over the elements in the collection.
5. add(E e): Adds an element to the collection.
6. remove(Object o): Removes the first occurrence of the specified element.
7. containsAll(Collection<?> c): Returns true if the collection contains all elements of the specified
collection.
8. addAll(Collection<? extends E> c): Adds all elements of the specified collection to this collection.
9. removeAll(Collection<?> c): Removes all elements of the specified collection from this collection.
10. retainAll(Collection<?> c): Retains only the elements that are contained in the specified collection.
11. clear(): Removes all elements from the collection.
12. toArray(): Returns an array containing all elements in the collection.

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.

example of how to use the Collection interface:

Collection<String> collection = new ArrayList<>();


collection.add("apple");
collection.add("banana");
System.out.println(collection.size()); // Output: 2
System.out.println(collection.contains("apple")); // Output: true

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.

Key features of the List interface:

1. Ordered collection: Elements are maintained in a specific order.


2. Indexing: Elements can be accessed using an integer index.
3. Positional access: Elements can be inserted or removed at specific positions.

Methods defined in the List interface:

1. get(int index): Returns the element at the specified index.


2. set(int index, E element): Replaces the element at the specified index.
3. add(int index, E element): Inserts an element at the specified index.
4. remove(int index): Removes the element at the specified index.
5. indexOf(Object o): Returns the index of the first occurrence of the specified element.
6. lastIndexOf(Object o): Returns the index of the last occurrence of the specified element.

Types of Lists:
1. ArrayList: A resizable array implementation.
2. LinkedList: A linked list implementation.
3. Vector: A legacy implementation (similar to ArrayList).

Example:

List<String> list = new ArrayList<>();


list.add("apple");
list.add("banana");
System.out.println(list.get(0)); // Output: "apple"
list.set(0, "cherry");
System.out.println(list.get(0)); // Output: "cherry"

** 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.

some key aspects of ArrayList:


- Implementation: ArrayList uses a dynamic array to store elements, which means it can grow or shrink
in size as elements are added or removed.
- Resizing: When the array is full, ArrayList creates a new array with a larger capacity and copies the
existing elements to the new array.
- Performance: ArrayList provides constant-time performance for get and set operations, making it
suitable for most use cases.
- Capacity: ArrayList's capacity grows automatically as elements are added, but it can also be manually
set using the ensureCapacity method.
- - Fail-fast iterator*: ArrayList's iterator is fail-fast, meaning it will throw a
ConcurrentModificationException if the list is modified while iterating.

Common use cases for ArrayList:


- Creating a list of objects: ArrayList<String> list = new ArrayList<>();
- Adding elements: list.add("element");
- Accessing elements: String element = list.get(0);
- Modifying elements: list.set(0, "newElement");

example of using ArrayList:


ArrayList<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
System.out.println(list.get(0)); // Output: "apple"
list.set(0, "cherry");
System.out.println(list.get(0)); // Output: "cherry"

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.

Here are some key aspects of LinkedList:

- 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.

Common use cases for LinkedList:

- 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.

example of using LinkedList:

LinkedList<String> list = new LinkedList<>();


list.add("apple");
list.add("banana");
System.out.println(list.get(0)); // Output: "apple"
list.remove(0);
System.out.println(list.get(0)); // Output: "banana"

** LinkedList is a generic class, allowing for type safety and flexibility.

how LinkedList fits into the Java Collection Framework:

- 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:

- Efficient insertion and deletion operations


- Good performance for frequent modifications
- Ability to implement queues, stacks, and other data structures

Vector- is a legacy class that implements the List interface. It is similar to ArrayList, but with some key
differences:

- Vector is synchronized, meaning it is thread-safe, whereas ArrayList is not.


- Vector has a capacity increment policy, whereas ArrayList has a dynamic growth policy.
- Vector is legacy and largely replaced by ArrayList, but still used in some legacy code.
example of using Vector:
Vector<String> vector = new Vector<>();
vector.add("apple");
vector.add("banana");
System.out.println(vector.get(0)); // Output: "apple"

** Vector is a legacy class and is not commonly used in new code.

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.

key features of the Stack class:


- push(E item): Adds an element to the top of the stack.
- pop(): Removes and returns the top element from the stack.
- peek(): Returns the top element without removing it.
- isEmpty(): Checks if the stack is empty.
- search(Object o): Searches for an element in the stack.

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.

example of using the Stack class:

Stack<String> stack = new Stack<>();


stack.push("apple");
stack.push("banana");
System.out.println(stack.pop()); // Output: "banana"

*** 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.

key methods defined in the Queue interface:


- add(E e): Inserts an element into the queue.
- offer(E e): Inserts an element into the queue, returning a boolean indicating success.
- remove(): Removes and returns the head of the queue.
- poll(): Removes and returns the head of the queue, or returns null if the queue is empty.
- element(): Returns the head of the queue, without removal.
- peek(): Returns the head of the queue, without removal, or returns null if the queue is empty.

The Queue interface has several implementations, including:

- ArrayDeque: A resizable array implementation.


- LinkedList: A linked list implementation.
- PriorityQueue: A priority-based implementation.

Queues are commonly used in:

- Job scheduling
- Print queues
- Network protocols
- Thread pools

example of using the Queue interface:

Queue<String> queue = new ArrayDeque<>();


queue.add("apple");
queue.add("banana");
System.out.println(queue.poll()); // Output: "apple"

*** 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.

key methods defined in the Set interface:

- add(E e): Adds an element to the set.


- remove(Object o): Removes an element from the set.
- contains(Object o): Checks if the set contains an element.
- size(): Returns the number of elements in the set.
- isEmpty(): Checks if the set is empty.
- iterator(): Returns an iterator over the elements in the set.

The Set interface has several implementations, including:

- HashSet: A hash-based implementation.


- LinkedHashSet: A linked hash-based implementation.
- TreeSet: A tree-based implementation.
Sets are commonly used in:

- Removing duplicates from a collection


- Checking membership in a collection
- Performing set operations (union, intersection, difference)

example of using the Set interface:

Set<String> set = new HashSet<>();


set.add("apple");
set.add("banana");
System.out.println(set.contains("apple")); // Output: true

** 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.

key features of HashSet:

- 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.

methods of HashSet include:


- add(E e): Adds an element to the set.
- remove(Object o): Removes an element from the set.
- contains(Object o): Checks if the set contains an element.
- size(): Returns the number of elements in the set.
- isEmpty(): Checks if the set is empty.

example of using HashSet:


HashSet<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
System.out.println(set.contains("apple")); // Output: true

**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.

key features of LinkedHashSet:


- Hash-based storage: LinkedHashSet uses a hash table to store elements, which provides fast lookup,
insertion, and removal operations.
- No duplicates: LinkedHashSet does not allow duplicate elements.
- Ordered: LinkedHashSet preserves the order of elements, based on the order in which they were
inserted.
- Null elements: LinkedHashSet allows null elements.
- Performance: LinkedHashSet provides constant-time performance for basic operations like add,
remove, and contains.

methods of LinkedHashSet include:

- add(E e): Adds an element to the set.


- remove(Object o): Removes an element from the set.
- contains(Object o): Checks if the set contains an element.
- size(): Returns the number of elements in the set.
- isEmpty(): Checks if the set is empty.

Example of using LinkedHashSet:

LinkedHashSet<String> set = new LinkedHashSet<>();


set.add("apple");
set.add("banana");
System.out.println(set.contains("apple")); // Output: true

// Iterating over the elements in the order they were inserted


for (String element : set) {
System.out.println(element);
}

**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.

key features of the SortedSet interface:

- 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.

methods of the SortedSet interface include:


- first(): Returns the first element in the sorted set.
- last(): Returns the last element in the sorted set.
- headSet(E toElement): Returns a subset of elements less than the specified element.
- tailSet(E fromElement): Returns a subset of elements greater than or equal to the specified element.
- subSet(E fromElement, E toElement): Returns a subset of elements between the specified elements.

The SortedSet interface has several implementations, including:


- TreeSet: A tree-based implementation.

example of using the SortedSet interface:


SortedSet<String> sortedSet = new TreeSet<>();
sortedSet.add("apple");
sortedSet.add("banana");
System.out.println(sortedSet.first()); // Output: "apple"

** 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.

key features of TreeSet:

- 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).

methods of TreeSet include:


- add(E e): Adds an element to the set.
- remove(Object o): Removes an element from the set.
- contains(Object o): Checks if the set contains an element.
- first(): Returns the first element in the set.
- last(): Returns the last element in the set.
- headSet(E toElement): Returns a subset of elements less than the specified element.
- tailSet(E fromElement): Returns a subset of elements greater than or equal to the specified element.
- subSet(E fromElement, E toElement): Returns a subset of elements between the specified elements.

example of using TreeSet:

TreeSet<String> treeSet = new TreeSet<>();


treeSet.add("apple");
treeSet.add("banana");
System.out.println(treeSet.first()); // Output: "apple"

**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.

key features of the Map interface:

- Key-value pairs: Map stores elements as key-value pairs.


- Unique keys: Map does not allow duplicate keys.
- Null keys and values: Map allows null keys and values, depending on the implementation.
- Retrieval and removal: Map provides methods for retrieving and removing elements based on their
keys.

methods of the Map interface include:

- put(K key, V value): Inserts a key-value pair into the map.


- get(Object key): Retrieves the value associated with the specified key.
- remove(Object key): Removes the key-value pair with the specified key.
- containsKey(Object key): Checks if the map contains the specified key.
- size(): Returns the number of key-value pairs in the map.
- isEmpty(): Checks if the map is empty.

The Map interface has several implementations, including:

- HashMap: A hash-based implementation.


- LinkedHashMap: A linked hash-based implementation.
- TreeMap: A tree-based implementation.

example -

Map<String, Integer> map = new HashMap<>();


map.put("apple", 5);
System.out.println(map.get("apple")); // Output: 5

**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.

key features of HashMap:


- Hash-based storage: HashMap uses a hash table to store key-value pairs, which provides fast lookup,
insertion, and removal operations.
- Key-value pairs: HashMap stores elements as key-value pairs.
- Unique keys: HashMap does not allow duplicate keys.
- Null keys and values: HashMap allows one null key and multiple null values.
- Efficient operations: HashMap provides constant-time performance for basic operations like put, get,
and remove.

methods of HashMap include:

- put(K key, V value): Inserts a key-value pair into the map.


- get(Object key): Retrieves the value associated with the specified key.
- remove(Object key): Removes the key-value pair with the specified key.
- containsKey(Object key): Checks if the map contains the specified key.
- size(): Returns the number of key-value pairs in the map.
- isEmpty(): Checks if the map is empty.

example of using HashMap:

HashMap<String, Integer> map = new HashMap<>();


map.put("apple", 5);
System.out.println(map.get("apple")); // Output: 5

**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.

key features of LinkedHashMap:


- Hash-based storage: LinkedHashMap uses a hash table to store key-value pairs, which provides fast
lookup, insertion, and removal operations.
- Linked list ordering: LinkedHashMap maintains a doubly-linked list of entries, which allows for efficient
iteration and insertion/removal of elements.
- Ordered iteration: LinkedHashMap provides ordered iteration over the key-value pairs, either in the
order they were inserted or in the order they were last accessed.
- Unique keys: LinkedHashMap does not allow duplicate keys.
- Null keys and values: LinkedHashMap allows one null key and multiple null values.
- Efficient operations: LinkedHashMap provides constant-time performance for basic operations like put,
get, and remove.

methods of LinkedHashMap include:

- put(K key, V value): Inserts a key-value pair into the map.


- get(Object key): Retrieves the value associated with the specified key.
- remove(Object key): Removes the key-value pair with the specified key.
- containsKey(Object key): Checks if the map contains the specified key.
- size(): Returns the number of key-value pairs in the map.
- isEmpty(): Checks if the map is empty.

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.

key features of TreeMap:


- Tree-based storage: TreeMap uses a self-balancing binary search tree to store key-value pairs, which
provides efficient sorting and searching capabilities.
- Sorted keys: TreeMap sorts keys according to their natural ordering or a specified Comparator.
- Unique keys: TreeMap does not allow duplicate keys.
- Null keys and values: TreeMap allows null values, but not null keys.
- Efficient operations: TreeMap provides efficient operations for adding, removing, and searching
elements, with a time complexity of O(log n).

methods of TreeMap include:


- put(K key, V value): Inserts a key-value pair into the map.
- get(Object key): Retrieves the value associated with the specified key.
- remove(Object key): Removes the key-value pair with the specified key.
- containsKey(Object key): Checks if the map contains the specified key.
- size(): Returns the number of key-value pairs in the map.
- isEmpty(): Checks if the map is empty.
- firstKey(): Returns the first key in the map.
- lastKey(): Returns the last key in the map.
- headMap(K toKey): Returns a view of the portion of the map whose keys are less than the specified
key.
- tailMap(K fromKey): Returns a view of the portion of the map whose keys are greater than or equal to
the specified key.

example
TreeMap<String, Integer> map = new TreeMap<>();
map.put("apple", 5);
System.out.println(map.get("apple")); // Output: 5

**TreeMap is a generic class, allowing for type safety and flexibility.

** 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.

example that illustrates the difference:

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).

methods of a hash table class include:

- put(K key, V value): Inserts a key-value pair into the map.


- get(Object key): Retrieves the value associated with the specified key.
- remove(Object key): Removes the key-value pair with the specified key.
- containsKey(Object key): Checks if the map contains the specified key.
- size(): Returns the number of key-value pairs in the map.
- isEmpty(): Checks if the map is empty.

Note that HashMap and Hashtable have some differences:

- HashMap is not synchronized, while Hashtable is synchronized.


- HashMap allows null keys and values, while Hashtable does not allow null keys or values.

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.

The Comparable interface has a single method:

- compareTo(Object obj): This method compares the current object with the specified object and returns
an integer.

The return value of the compareTo method is as follows:

- 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

public class Student implements Comparable<Student> {


private int rollNumber;
private String name;

public Student(int rollNumber, String name) {


this.rollNumber = rollNumber;
this.name = name;
}

public int compareTo(Student otherStudent) {


return this.rollNumber - otherStudent.rollNumber;
}
}

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.

benefits of using the Comparable interface include:

- Customized sorting and ordering of objects


- Improved code reusability and flexibility
- Enhanced data structure and algorithm capabilities

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.

The return value of the compare method is as follows:


- Negative integer: if obj1 is less than obj2.
- Zero: if obj1 is equal to obj2.
- Positive integer: if obj1 is greater than obj2.

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.

benefits of using the Comparator interface include:

- Customized comparison and ordering of objects


- Improved code reusability and flexibility
- Enhanced data structure and algorithm capabilities

**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

Properties Class in Java


The Properties class in Java is used to handle configuration data or application settings . It represents a
persistent set of properties that can be saved to a stream or loaded from a stream .

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 .

Commonly Used Methods:

- 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;

public class PropertiesExample {


public static void main(String[] args) {
Properties props = new Properties();

// Set properties
props.setProperty("name", "John");
props.setProperty("age", "30");

// Get properties
String name = props.getProperty("name");
String age = props.getProperty("age");

System.out.println("Name: " + name);


System.out.println("Age: " + age);
}
}

You might also like