0% found this document useful (0 votes)
30 views49 pages

Abc2 Java Collections

Download as pptx, pdf, or txt
0% found this document useful (0 votes)
30 views49 pages

Abc2 Java Collections

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1/ 49

Java Collections

Collection
• If we want to represent a group of objects as single entity then we should go for
collections.
• Collection framework:
It defines several classes and interfaces to represent a group of objects as a single
entity.
9(Nine) key interfaces of collection framework:
1. Collection
2. List
3. Set
4. SortedSet
5. NavigableSet
6. Queue
7. Map
8. SortedM ap
9. NavigableM ap
Collection interface ( Root Interface )
1. If we want to represent a group of "individual objects" as a single entity then we
should go for collection..
2. In general we can consider collection as root interface of entire collection
framework.
3. Collection interface defines the most common methods which can be applicable
for any collection object.

4. There is no concrete class which implements Collection interface directly .


Methods in collection interface
1. boolean add(Object o);
2. boolean addAll(Collection c);
3. boolean remove(Object o);
4. boolean removeAll(Object o);
5. boolean retainAll(Collection c); //To remove all objects except those present in c.
6. Void clear();
7. boolean contains(Object o);
8. boolean containsAll(Collection c);
9. boolean isEmpty();
10. Int size();
11. Object[] toArray();
12. Iterator iterator()
There is no concrete class which implements Collection interface directly.
So all this methods, we can use in the concrete class which are implments collection child
List interface
1. It is the child interface of Collection.
2. If we want to represent a group of individual objects as a single entity where duplicates
are allow and insertion order is preserved. Then we should go for List.
3. We can differentiate duplicate objects and we can maintain insertion order by means of
index hence "index play very important role in List".
4. List interface defines the specific methods.
1. boolean add(int index,Object o);
2. boolean addAll(int index,Collectio c);
3. Object get(int index);
4. Object remove(int index);
5. Object set(int index,Object new);/ / to replace
6. Int indexOf(Object o);
Returns index of first occurrence of "o".
7. Int lastIndexOf(Object o);
8. ListIterator listIterator();
ArrayList ( Class )
 The underlying data structure is resizable array (or) growable array.
 Duplicate objects are allowed.
 Insertion order preserved.
 Heterogeneous objects are allowed.(except TreeSet , TreeM ap every where
heterogenious objects are allowed)
 Null insertion is possible. Not Synchronized, multiple thread run, high performance.
ArrayList Constructors:
1. ArrayList a=new ArrayList(); // default initial capacity is 10, if arraylist reachest max
capacity mean if it fill 75% of arraylist then new arraylist will create.
2. ArrayList a=new ArrayList(int initialcapacity);
Creates an empty ArrayList object with the specified initial capacity.
3. ArrayList a=new ArrayList(collection c);
Creates an equivalent ArrayList object for the given Collection that is this
constructor meant for inter conversation between collection objects.
LinkedList ( Class )
 The underlying data structure is is double LinkedList.
 Duplicate objects are allowed.
 Insertion order preserved.
 Heterogeneous objects are allowed.(except TreeSet , TreeM ap every where
heterogenious objects are allowed)
 Null insertion is possible. Not Synchronized, multiple thread run, high performance.
 If our frequent operation is insertion (or) deletion in the middle then LinkedList is
the best choice.
 If our frequent operation is retrieval operation then LinkedList is worst choice.
Double linkedlist
Methods of Linkedlist
o void addFirst(Object o);
o void addLast(Object o);
o Object getFirst();
o Object getLast();
o Object removeFirst();
o Object removeLast();
We can apply these methods only on LinkedList object.
Constructors :LinkedList l=new LinkedList(); // Creates an empty LinkedList obj
LinkedList l=new LinkedList(Collection c);
To create an equivalent LinkedList object for the given collection.
Example :
Vector Class
 The underlying data structure is resizable array (or) growable array.
 Duplicate objects are allowed. Insertion order is preserved.
 Heterogeneous objects are allowed. Null insertion is possible.
 Implements Serializable, Cloneable and RandomAccess interfaces.
 Every method present in Vector is synchronized and hence Vector is Thread
safe.
Vector specified methods
• addElement(Object o);
• removeElement(Object o);
• removeElementAt(int index);
• RemoveAllElements();
• Object firstElement();
• Object lastElement();
• Int size();/ / How many objects are added
• Int capacity();/ / Total capacity
• Enumeration elements();
Vector constructors
• Vector v=new Vector();
Creates an empty Vector object with default initial capacity 10.
Once Vector reaches its maximum capacity then a new Vector object will be
created with double capacity. That is "newcapacity=currentcapacity* 2".
• Vector v=new Vector(int initialcapacity);
• Vector v=new Vector(int initialcapacity, int incrementalcapacity);
• Vector v=new Vector(Collection c);
• Example :
Stack class
• It is the child class of Vector.
• Whenever last in first out(LIFO) order required then we should go for
Stack.
• It contains only one constructor. Stack s= new Stack();
• Methods:
1. Object push(Object o); //To insert an object into the stack.
2. Object pop(); //To remove and return top of the stack.
3. Object peek(); //To return top of the stack without removal.
4. boolean empty(); //Returns true if Stack is empty.
5. Int search(Object o); //Returns offset if the element is available
otherwise returns "-1"
The 3 cursors in java

1. Enumeration
2. Iterator
3. ListIterator
1. Enumeration (java 1.0 V)
• We can use Enumeration to get objects one by one from the legacy
collection objects.
• We can create Enumeration object by using elements() method.

• public Enumeration elements();


Enumeration e=v.elements();
using Vector Object
• Enumeration has 2 methods
1.public boolean hasM oreElements();
2. public Object nextElement();
Limitations of Enumeration:
1. We can apply Enumeration concept only for legacy classes and it is not a
universal cursor.
2. By using Enumeration we can get only read access and we can't perform
remove operations.
3. To overcome these limitations sun people introduced Iterator concept
in 1.2v.
2. Iterator (java 1.2 V)
• We can use Iterator to get objects one by one from any collection object.
• We can apply Iterator concept for any collection object and it is a universal cursor.
• While iterating the objects by Iterator we can perform both read and remove
operations.
• We can get Iterator object by using iterator() method of Collection interface.

public Iterator iterator();
Iterator itr=c.iterator();
Methods of Iterator
1. public boolean hasNext();
2. public object next();
3. public void remove();
4. Example :
 Limitations of Iterator:

1. Both enumeration and Iterator are single direction cursors only. That is we can
always move only forward direction and we can't move to the backward direction.
2. While iterating by Iterator we can perform only read and remove operations and
we can't perform replacement and addition of new objects.
3. To overcome these limitations sun people introduced listIterator concept.
ListIterator (java 1.2 V)
1. ListIterator is the child interface of Iterator.
2. By using listIterator we can move either to the forward direction (or) to the
backward direction that is it is a bi-directional cursor.
3. While iterating by listIterator we can perform replacement and addition of new
objects in addition to read and remove operations
4. By using listIterator method we can create listIterator object.
public ListIterator listIterator();
ListIterator itr=l.listIterator(); // (l is any List object)
Methods of listiterator
1. public boolean hasNext();
2. public Object next(); forward
3. public int nextIndex();
4. public boolean hasPrevious();
5. public Object previous(); backward
6. public int previousIndex();
7. public void remove();
8. public void set(Object new);
9. public void add(Object new);
Enumeration Iterator and ListIterator ?
Property Enumeration Iterator ListIterator

Is it legacy ? Yes No No

It is applicable for? Only legacy classes Applicable for any Applicable for only list
collection object objects
moment Single direction Single direction Bi- direction

How to get it ? By using elements() method By using iterator() By using listiterator()


method method
accessibility Only read Only read and remove read/remove/replace/
add
methods hasMoreElement() hasNext() 9 methods
nextElement() next() ,remove()
Set interface
• It is the child interface of Collection.
If we want to represent a group of individual objects as a single entity where
duplicates are not allow and insertion order is not preserved then we should go
for Set interface.
• Set interface does not contain any new method we have to use only Collection
interface methods.
HashSet interface
1. The underlying data structure is Hashtable.
2. Insertion order is not preserved and it is based on hash code of the objects.
3. Duplicate objects are not allowed.
4. If we are trying to insert duplicate objects we won't get compile time error and
runtime error add() method simply returns false.
5. Heterogeneous objects are allowed.
6. Null insertion is possible.(only once)
7. Implements Serializable and Cloneable interfaces but not RandomAccess.
8. HashSet is best suitable, if our frequent operation is "Search".
Constructors of HashSet
1. HashSet h=new HashSet();
Creates an empty HashSet object with default initial capacity 16 and default fill
ratio 0.75(fill ratio is also known as load factor).
2. HashSet h=new HashSet(int initialcapacity);
Creates an empty HashSet object with the specified initial capacity and default fill
ratio 0.75.
3. HashSet h=new HashSet(int initialcapacity,float fillratio);
HashSet h=new HashSet(Collection c);
4. Note : After filling how much ratio new HashSet object will be created , The ratio is
called "FillRatio" or "LoadFactor".
5. Example ;
LinkedHashSet
HashSet (Child interface of Set ) LinkedHashSet (Child interface of Set)

The underlying data structure is The underlying data structure is a combination


Hashtable. of LinkedList and Hashtable.

Insertion order is not Insertion order is preserved


preserved.

Introduced in 1.2 v. 3) Introduced in 1.4v.


Example ;
TreeSet
1. The underlying data structure is balanced tree.
2. Duplicate objects are not allowed.
3. Insertion order is not preserved and it is based on some sorting order of
objects.
4. Heterogeneous objects are not allowed if we are trying to insert
heterogeneous objects then we will get ClassCastException.
5. For the empty TreeSet as the 1st element null insertion is possible in all
other cases we will get Null pointer Exception.
Constructors of TreeSet
1. TreeSet t=new TreeSet();
Creates an empty TreeSet object where all elements will be inserted according to
default natural sorting order.
2. TreeSet t=new TreeSet(Comparator c);
Creates an empty TreeSet object where all objects will be inserted according to
customized sorting order specified by Comparator object.
3. TreeSet t=new TreeSet(SortedSet s);
TreeSet t=new TreeSet(Collection c);
comparable
• Comparable interface is used to define a natural ordering of objects.
• When a class implements the Comparable interface, it means instances of that class
can be compared with each other based on a predefined ordering.
• Interface Definition:
• The Comparable interface is in the java.lang package.
• It declares a single method: int compareTo(T obj), where T is the type of objects
being compared.
• Natural Ordering:
• Implementing Comparable suggests that instances of the class have a natural
ordering.
• The natural ordering is typically based on one or more of the object's fields.
• Sorting:
• Objects that implement Comparable can be easily sorted using utility methods
like Collections.sort() or Arrays.sort().
• Return Values of compareTo:
• The compareTo method should return a negative integer, zero, or a positive
integer based on whether the current object is less than, equal to, or greater
than the specified object, respectively.
• Consistent with Equals:
• The natural ordering defined by compareTo should be consistent with the
equals method.
• If compareTo returns zero for two objects, their equals method should return
true
• import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

class Student implements Comparable<Student> {


private String name;
private int age;

// Constructors, getters, setters...

@Override
public int compareTo(Student other) {
// Compare based on age
return Integer.compare(this.age, other.age);
}
}

public class ComparableExample {


public static void main(String[] args) {
List<Student> students = new ArrayList<>();
students.add(new Student("Alice", 22));
students.add(new Student("Bob", 20));
students.add(new Student("Charlie", 25));

// Sorting students based on natural ordering (age)


Collections.sort(students);

// Displaying sorted list


for (Student student : students) {
System.out.println(student.getName() + " - " + student.getAge() + " years old");
}
}
}
comparator
• Comparable interface is used to define a customize ordering of objects.
• This is particularly useful when you want to sort objects based on criteria other
than their natural ordering.
• Interface Definition:
• The Comparator interface is also in the java.util package.
• It declares two methods: int compare(T obj1, T obj2) and boolean equals(Object
obj).
• Custom Ordering:
• Unlike Comparable, which is for the natural ordering of objects, Comparator
allows you to define custom ordering logic separate from the object's class.
• External Sorting:
• You can use a Comparator to sort objects in a way that is different from their
natural ordering.
• Multiple Sorting Criteria:
• Comparator allows you to define multiple sorting criteria or change the sorting
order dynamically.

class Person {
private String name;
private int age;

// Constructors, getters, setters...

// Static comparator for comparing persons based on their names


public static Comparator<Person> NameComparator = Comparator.comparing(Person::getName);

// Another comparator for comparing persons based on their ages


public static Comparator<Person> AgeComparator = Comparator.comparingInt(Person::getAge);
}

public class ComparatorExample {


public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 22));
people.add(new Person("Bob", 20));
people.add(new Person("Charlie", 25));

// Sorting people based on names using NameComparator


Collections.sort(people, Person.NameComparator);

// Displaying sorted list


System.out.println("Sorted by Name:");
for (Person person : people) {
System.out.println(person.getName() + " - " + person.getAge() + " years old");
}

// Sorting people based on ages using AgeComparator


Collections.sort(people, Person.AgeComparator);

// Displaying sorted list


System.out.println("\nSorted by Age:");
for (Person person : people) {
System.out.println(person.getName() + " - " + person.getAge() + " years old");
}
}
}
Comparable Comparator
Interface Location java.lang.Comparable java.util.Comparator
Purpose Defines natural ordering of objects Provides external ordering of objects
in a class
Method int compareTo(T obj) int compare(T obj1, T obj2)
Implementation Implemented by the class of the Implemented as a separate class or in
objects being compared the same class as the objects being
compared
Single/Multiple Criteria Typically for the natural order Can handle multiple criteria or dynamic
based on a single criterion sorting
Usage in Sorting Used by sorting methods like Passed explicitly to sorting methods
Collections.sort or Arrays.sort
Null Handling The class itself defines how null is Can be customized by the Comparator
handled in compareTo implementation
Consistency with equals Expected to be consistent with Not necessarily related to equals
equals method method
Map
• If we want to represent a group of objects as "key-value" pair then we should go
for Map interface.
• Map interface is not child interface of Collection and hence we can't apply
Collection interface methods here.
• Both key and value are objects only.
• Duplicate keys are not allowed but values can be duplicated
• Each key-value pair is called "one entry".
Methods of Map interface
1. Object put(Object key,Object value); //To add an entry to the M ap, if key is already available
then the old value replaced with new value and old value will be returned.
2. void putAll(M ap m);
3. Object get(Object key);
4. Object remove(Object key); //It removes the entry associated with specified key and returns the
corresponding value.
5. boolean containsKey(Object key);
6. boolean containsValue(Object value);
7. boolean isEmpty();
8. Int size();
9. void clear();
10. Set keySet(); //The set of keys we are getting.
11. Collection values(); //The set of values we are getting.
12. Set entrySet(); //The set of entryset we are getting.
HashMap
1. The underlying data structure is Hashtable.
2. Duplicate keys are not allowed but values can be duplicated.
3. Insertion order is not preserved and it is based on hash code of the keys.
4. Heterogeneous objects are allowed for both key and value.
5. Null is allowed for keys(only once) and for values(any number of times).
6. It is best suitable for Search operations.
Constructors
1. HashMap m=new HashMap();
Creates an empty HashMap object with default initial capacity 16 and default fill
ratio "0.75".
2. HashMap m=new HashMap(int initialcapacity);
3. HashMap m =new HashMap(int initialcapacity, float fillratio);
4. HashMap m=new HashMap(Map m);
LinkedHashMap
• HashMap • LinkedHashMap
• The underlying data structure • The underlying data structure is a
is Hashtable. combination of Hashtable+ LinkedList.
• Insertion order is not • Insertion order is preserved.
Preserved.
• Introduced in 1.4v.
• introduced in 1.2.v. 3)
• Example :
ConcurrentHashMap
• Introduce in java 1.5 V
• Used in multithread environment
• Main difference between hashmap and concurrentHashMap is all the table
divide into the segment so in one segment 1 thread is writing something then
other thread can be read. But in hashMap hole table will be lock.not only
particular segment.
HashTable
1. The underlying data structure is Hashtable.
2. Insertion order is not preserved and it is based on hash code of the keys.
3. Heterogeneous objects are allowed for both keys and values.
4. Null key (or) null value is not allowed otherwise we will get NullPointerException.
5. Duplicate keys are allowed but values can be duplicated.
6. Every method present inside Hashtable is syncronized and hence Hashtable objet is
Thread-safe.
HashTable constructors
1. Hashtable h=new Hashtable();
Creates an empty Hashtable object with default initialcapacity 11 and default fill
ratio 0.75.
2. Hashtable h=new Hashtable(int initialcapacity);
3. Hashtable h=new Hashtable(int initialcapacity,float fillratio);
4. Hashtable h=new Hashtable (Map m);
HashMap
• Key-Value Pairs:
• HashMap stores data in the form of key-value pairs.
• Each key must be unique within the HashMap.
• Null Keys and Values:
• HashMap allows one null key and multiple null values.
• Performance:
• Provides constant-time complexity O(1) for basic operations (get and put) on average.
• The actual performance might degrade if the load factor increases, causing rehashing.
• Not Thread-Safe:
• HashMap is not synchronized, making it not suitable for concurrent operations.
• import java.util.HashMap;

public class HashMapExample {


public static void main(String[] args) {
// Creating a HashMap
HashMap<String, Integer> studentAges = new HashMap<>();

// Adding key-value pairs


studentAges.put("Alice", 25);
studentAges.put("Bob", 22);
studentAges.put("Charlie", 28);

// Accessing values
System.out.println("Age of Bob: " + studentAges.get("Bob"));

// Iterating through the HashMap


for (String name : studentAges.keySet()) {
System.out.println(name + " is " + studentAges.get(name) + " years old.");
}
}
}
Internal Working and Implementation:
• Hashing:
• The HashMap uses the key's hash code to determine the index where the key-value pair should
be stored.
• The hashCode() method of the key object is used to calculate the hash code.
• Buckets:
• Internally, a HashMap is an array of linked lists (buckets).
• Each bucket stores key-value pairs that have the same hash code (collision resolution).
• Load Factor and Rehashing:
• HashMap uses a load factor to determine when to resize the array of buckets.
• When the number of entries exceeds the product of the load factor and the current capacity, the
map is resized and rehashed.
• Chaining:
• In case of hash code collisions, entries are stored as nodes in a linked list in the same bucket.
• If a bucket becomes too populated, it may be converted into a balanced tree to improve search
Queue interface ( java 1.5 V)
• Queue is child interface of Collections.

• If we want to represent a group of individual objects prior (happening before


something else) to processing then we should go for Queue interface.

• Usually Queue follows first in first out(FIFO) order but based on our requirement we
can implement our own order also.

• From 1.5v onwards LinkedList also implements Queue interface. LinkedList based
implementation of Queue always follows first in first out order.

• Assume we have to send sms for one lakh mobile numbers , before sending
messages we have to store all mobile numbers into Queue so that for the first
inserted number first message will be triggered(FIFO).
Methods of Queue interface
• boolean affer(Object o);
To add an object to the Queue.
• Object poll() ;
To remove and return head element of the Queue, if Queue is empty then we
will get null.
• Object remove();
To remove and return head element of the Queue. If Queue is empty then this
method raises Runtime Exception saying NoSuchElementException.
• Object peek();
To return head element of the Queue without removal, if Queue is empty this
method returns null.
• Object element();
It returns head element of the Queue and if Queue is empty then it will raise
Runtime Exception saying NoSuchElementException.
PriorityQueue
• PriorityQueue is a data structure to represent a group of individual objects prior to
processing according to some priority.
• The priority order can be either default natural sorting order (or) customized sorting order
specified by Comparator object.
• If we are depending on default natural sorting order then the objects must be
homogeneous and Comparable otherwise we will get ClassCastException.
• If we are defining our own customized sorting order by Comparator then the objects need
not be homogeneous and Comparable.
• Duplicate objects are not allowed.
• Insertion order is not preserved but all objects will be inserted according to some
Priority.
• Null is not allowed even as the 1st element for empty PriorityQueue.Otherwise we
will get the "NullPointerException".
Constructor of priorityQueue
• PriorityQueue q=new PriorityQueue();
Creates an empty PriorityQueue with default initial capacity 11 and default
natural sorting order.
• PriorityQueue q=new PriorityQueue(int initialcapacity,Comparator c);
• PriorityQueue q=new PriorityQueue(int initialcapacity);
• PriorityQueue q=new PriorityQueue(Collection c);
• PriorityQueue q=new PriorityQueue(SortedSet s);

You might also like