[go: up one dir, main page]

0% found this document useful (0 votes)
24 views19 pages

6-Collection Part-6

The document provides an overview of various Java collection interfaces and classes, including Set, HashSet, LinkedHashSet, SortedSet, NavigableSet, and TreeSet, detailing their characteristics, constructors, and differences. It highlights key features such as element ordering, duplication rules, and internal data structures. Additionally, it explains how to implement custom sorting using Comparable and Comparator interfaces for user-defined classes.

Uploaded by

Tisha Arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views19 pages

6-Collection Part-6

The document provides an overview of various Java collection interfaces and classes, including Set, HashSet, LinkedHashSet, SortedSet, NavigableSet, and TreeSet, detailing their characteristics, constructors, and differences. It highlights key features such as element ordering, duplication rules, and internal data structures. Additionally, it explains how to implement custom sorting using Comparable and Comparator interfaces for user-defined classes.

Uploaded by

Tisha Arora
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Set:

• It was introduced in JDK 1.2 version.


• It is a direct child interface to Collection interface.
• It is not index based, it able to arrange all the elements on the basis of elements hashcode
values.
• It will not allow duplicate elements.
• It will not follow insertion order.
Note:
LinkedHashSet will follow insertion order.

• It will not follow Sorting order.


Note:
SortedSet, NavigableSet and TreeSet are following Sorting order.

• It able to allow only one null value.


Note:
SortedSet, NavigableSet and TreeSet are not allowing even single null value.

HashSet:
• HashSet is a direct implementation class to Set interface.
• It was introduced in JDK 1.2 version.
• It is not index based, it able to arrange all the elements on the basis of elements hashcode values.
• It will not allow duplicate elements.
• It will not follow insertion order.
• It will not follow Sorting order.
• It able to allow only one null value.
• Its interal data structure is "Hashtable".
• Its initial capacity is "16" elements and its initial fill_Ratio is 75%.
• It is not synchronized.
• Almost all the methods are not synchronized in HashSet
• It allows more than one thread at a time.
• It follows parallel execution.
• It will reduce execution time.
• It improves performance of the applications.
• It is not giving guarantee for data consistency.
• It is not threadsafe.

Constructors:
1) public HashSet()
This constructor can be used to create an empty HashSet object with 16 elements as initial
capacity and 75% fill ratio.

Ex:
If internal capacity is 16 and the load factor is 0.75 then the number of buckets will automatically get
increased when the table has 12 elements in it.
EX:
HashSet hs = new HashSet();

2) public HashSet(int capacity)


This constructor can be used to create an empty HashSet object with the specified capacity as
initial capacity and with the default fill ratio 75%.
EX:
HashSet hs = new HashSet(20);

3) public HashSet(int capacity, float fill_Ratio)


This constructor can be used to create an empty HashSet object with the specified capacity
and with the specified fill ratio.
EX:
HashSet hs = new HashSet(20, 0.85f);

4) public HashSet(Collection c)
This constructor can be used to create HashSet object with all the elements of the specified
Collection.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs1=new HashSet();
hs1.add("A");
hs1.add("B");
hs1.add("C");
hs1.add("D");
hs1.add("E");
System.out.println(hs1);
HashSet hs2=new HashSet(hs1);
System.out.println(hs2);
}
}

[D,E,A,B,C]
[D,E,A,B,C]
EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("A");
hs.add("B");
hs.add("C");
hs.add("D");
hs.add("E");
System.out.println(hs);
hs.add("B"); //It will not add B
System.out.println(hs);
hs.add(null);
hs.add(null);
System.out.println(hs);
hs.add(new Integer(10));
System.out.println(hs);
}
}

LinkedHashSet:
Que )
What are the differences between HashSet and LinkedHashSet?
Ans:
• HashSet was introduced in JDK 1.2 version.
LinkedhashSet was introduced in JDK 1.4 version.

• HashSet is not following insertion order.


LinkedHashSet is following insertion order.

• The internal data structure of HashSet is "Hashtable".


The internal data structure of LinkedHashSet is "Hashtable" and "LinkedList".

EX
import java.util.*;
class Test
{
public static void main(String[] args)
{
HashSet hs=new HashSet();
hs.add("A");
hs.add("B");
hs.add("C");
hs.add("D");
hs.add("E");
System.out.println(hs);

LinkedHashSet lhs=new LinkedHashSet();


lhs.add("A");
lhs.add("B");
lhs.add("C");
lhs.add("D");
lhs.add("E");
System.out.println(lhs);
}
}
OUTPUT:
[D,E,A,B,C]
[A,B,C,D,E]

SortedSet:

SoretedSet is an Interface.
• It was introduced in JDK1.2 version.
• It is a child interface to Set interface.
• It is not index based.
• It is not allowing duplicate elements.
• It is not following insertion order.
• It follows Sorting order.
• It allows only homogeneous elements.
• It will not allow heterogeneous elements, if we are trying to add heterogeneous elements then
JVM will rise an exception like java.lang.ClasscastException.

• It will not allow null values, if we are trying to add any null value then JVM will rise an exception
like java.lang.NullPointerException.

• It able to allow only Comparable objects by default, if we are trying to add non comparable
objects then JVM will rise an exception like java.lang.ClassCastException.

Note:
If we are trying to add non comparable objects then we have to use Comparator.

Methods of SortedSet interface:


public Object first()
It will return first element from SortedSet.
• public Object last()
It will return last element from SortedSet.
• public SortedSet headSet(Object obj)
It will return SortedSet object with the elements which are
less the specified element.
But the specified element is not included.

• public SortedSet tailSet(Object obj)


It will return SortedSet object with the elements which are
greater than or equals to the specified element.
Here specified element is included.
• public SortedSet subSet(Object obj1, Object obj2)
It will return SortedSet object with all elements which are greater than or equals to
the specified first element and which are less than the specified second element.

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add("D");
ts.add("F");
ts.add("B");
ts.add("E");
ts.add("C");
ts.add("A");

System.out.println(ts);
System.out.println(ts.first());
System.out.println(ts.last());
System.out.println(ts.headSet("D"));
System.out.println(ts.tailSet("D"));
System.out.println(ts.subSet("B","E"));
}
}

NavigableSet:
It was introduced in JAVA6 version, it is a child interface to SortedSet interface, it is following all the properties
of SortedSet and it has define methods to provide navigations over the elements.

Methods:
• public Object ceiling(Object obj)
It will return lowest element among all the elements which are greater than or equals to the specified
element.
• public Object higher(Object obj)
It will return lowest element among all the elements which are greater than the specified element.
• public Object floor(Object obj)
It will return highest element among all the elements which are less than or equals to the specified
element.

•public Object lower(Object obj)


It will return highest element among all the elements which are less than the specified element.
• public Object pollFirst()
It will remove and return first element from NavigableSet.
• public Object pollLast()
It will remove and return last element from NavigableSet.
• public NavigableSet descendingSet()
It will return all elements in the form of NavigableSet in
descending order.
EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add("D");
ts.add("F");
ts.add("B");
ts.add("E");
ts.add("C");
ts.add("A");
System.out.println(ts);
System.out.println(ts.ceiling("D"));
System.out.println(ts.higher("D"));
System.out.println(ts.floor("D"));
System.out.println(ts.lower("D"));
System.out.println(ts.descendingSet());
ts.pollFirst();
ts.pollLast();
System.out.println(ts);
}
}

TreeSet:
• It was introduced in JDK 1.2 version.
• It is not Legacy Collection.
• It has provided implementation for Collection, Set, SortedSet and NavigableSet interfaces.
• It is not index based.
• It is not allowing duplicate elements.
• It is not following insertion order.
• It follows Sorting order.
• It allows only homogeneous elements.
• It will not allow heterogeneous elements, if we are trying to add heterogeneous elements then JVM will
rise an exception like java.lang.ClasscastEx ception.
• It will not allow null values, if we are trying to add any null value then JVM will rise an exception like
java.lang.NullPointerException.
• It able to allow only Comparable objects by default, if we are trying to add non comparable objects then JVM
will rise an exception like java.lang.ClassCastException.

NOTE:
If we are trying to add non comparable objects then we have to use java.util.Comparator.
• Its internal data structure is "Balanced Tree".
• It is mainly for frequent search operations.

Constructors:
• public TreeSet()
It can be used to create an Empty TreeSet object.
EX:
TreeSet ts = new TreeSet();
• public TreeSet(Comparator c)
It will create an empty TreeSet object with the explicit Sorting mechanism in the form of
Comparator
EX:
TreeSet ts = new TreeSet(new MyComparator());

• public TreeSet(SortedSet ts)


It will create TreeSet object with all elements of the specified
SortedSet.
EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts1=new TreeSet();
ts1.add("B");
ts1.add("C");
ts1.add("F");
ts1.add("A");
ts1.add("E");
ts1.add("D");
System.out.println(ts1);
TreeSet ts2=new TreeSet(ts1);
System.out.println(ts2);
}
}

4) public TreeSet(Collection c)
It able to create TreeSet object with all the elements of the specified Collection.
EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
ArrayList al=new ArrayList();
al.add("B");
al.add("C");
al.add("F");
al.add("A");
al.add("E");
al.add("D");
System.out.println(al);
TreeSet ts=new TreeSet(al);
System.out.println(ts);
}
}

EX:
import java.util.*;
class Test
{
public static void main(String[] args)
{
TreeSet ts=new TreeSet();
ts.add("B");
ts.add("C");
ts.add("F");
ts.add("A");
ts.add("E");
ts.add("D");
System.out.println(ts);
ts.add("B");
System.out.println(ts);
//ts.add(null);--> NullPointerException
//ts.add(new Integer(10));-->ClassCastException
//ts.add(new StringBuffer("BBB"));->ClassCastException
}
}

When we add elements to the TreeSet object, TreeSet object will arrange all the elements in a particular sorting
order with the following algorithm.

• TreeSet will construct a Tree [Balanced Tree] on the basis of the elements.
To construct Balanced Tree we have to use the following steps.
• If the element is first element to the TreeSet object then make that element as "Root Node".
• If the element is not first element then access compareTo(--) method over the present element by passing
previous elements one by one of the balanced Tree right from root node until the present element is located in
Tree.
• If compareTo(-) method returns -ve value then go to left child of the present node and access again compareTo(-
) method by passing left child. If no left child is existed then make the present element as left child
• If compareTo(-) method returns +ve value then go to right child and access again compareTo(-) by passing right
as parameter. If no right child is existed then make the present element as right child.
• If compareTo(-) method return 0 value then discard the present element and declare that the present element is
a duplicate element of the existed element.

• TreeSet will retrieve all the elements from balanced Tree by following in order traversal.

In String class, compareTo(-) method was implemented like below str1.compareTo(str2);


• If str1 come first when compared with str2 as per dictionary order then compareTo() method will return -ve
value.
• If str2 come first when compared with str1 in dictionary order then compareTo() method will return +ve value.
• If str1 and str2 are same or available at same location in dictionary order then compareTo(-) method will return
0 value.

If we want to add user defined elements like Employee, Student, Customer to TreeSet then we have to use the
following steps.

• Declare an user defined class.


• Implement java.lang.Comparable iterface in User defined class.
• Provide implementation for compareTo(-) method in user defined class.
• In main class, in main() method, create objects for user defined class and add objects to TreeSet object.

Ex:

import java.util.TreeSet;
class Employee implements Comparable{
int eno;
String ename;
float esal;
String eaddr;

public Employee(int eno, String ename, float esal, String eaddr){


this.eno = eno;
this.ename = ename;
this.esal = esal;
this.eaddr = eaddr;
}

@Override
public int compareTo(Object obj) {
Employee emp = (Employee)obj;
int val = 0;
val= this.ename.compareTo(emp.ename);
return val;
}

@Override
public String toString() {
return "\nEmployee{" +
"eno=" + eno +
", ename='" + ename + '\'' +
", esal=" + esal +
", eaddr='" + eaddr + '\'' +
'}';
}
}
public class Test {
public static void main(String[] args) {
Employee emp1 = new Employee(111, "DD", 5000, "AGR");
Employee emp2 = new Employee(222, "Neelesh", 6000, " AGR ");
Employee emp3 = new Employee(333, "Aishwary", 7000, " AGR ");
Employee emp4 = new Employee(444, "Gopi Krishna", 8000, " AGR");
Employee emp5 = new Employee(555, "Tahauddin", 9000, " AGR");

TreeSet ts = new TreeSet();


ts.add(emp1);
ts.add(emp2);
ts.add(emp3);
ts.add(emp4);
ts.add(emp5);
System.out.println(ts);
}
}

If we add non-comparable objects to TreeSet object then JVM will rise an exception like
java.lang.ClassCastException, because, Non-Comparable objects are not providing compareTo(-) method
internally, but, it is required to the TreeSet inorder to provide sorting order over elements.
If we want to add non-Comparable objects to TreeSet object then we must provide sorting logic to TreeSet object
explicitly, for this, we have to use java.util.Comparator interface.

If we want to use Comparator interface in java applications then we have to use the following steps.

• Declare an User defined class.


• Implement java.util.Comparator interface in user defined class.
• Provide implementation for Comparator interface methods in user defined class.

public boolean equals(Object obj)


public int compare(Object obj1, Object obj2)

Note:
In User defined class it is not required to implement equals(-) method, because, equals(-)
method will come from default super class Object.

• Provide User defined Comparator object to TreeSet object

EX:
MyComparator mc = new MyComparator();
TreeSet ts = new TreeSet(mc);

EX:
import java.util.*;
class MyComparator implements Comparator
{

public int compare(Object obj1, Object obj2)


{
StringBuffer s1=(StringBuffer)obj1;
StringBuffer s2=(StringBuffer)obj2;

int length1=s1.length();
int length2=s2.length();
int val=0;
if(length1<length2)
{
val=-100;
}
else if(length1>length2)
{
val=100;
}
else
{
val=0;
}
return val;
}
}
class Test
{
public static void main(String[] args)
{
StringBuffer sb1=new StringBuffer("AAA");
StringBuffer sb2=new StringBuffer("BB");
StringBuffer sb3=new StringBuffer("CCCC");
StringBuffer sb4=new StringBuffer("D");
StringBuffer sb5=new StringBuffer("EEEEE");
MyComparator mc=new MyComparator();
TreeSet ts=new TreeSet(mc);
ts.add(sb1);
ts.add(sb2);
ts.add(sb3);
ts.add(sb4);
ts.add(sb5);
System.out.println(ts);
}
}

EX:
import java.util.*;
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)
{
Student s1=(Student)obj1;
Student s2=(Student)obj2;
int val=s1.saddr.compareTo(s2.saddr);
return -val;
}
}
class Student
{

String sid;
String sname;
String saddr;

Student(String sid, String sname, String saddr)


{
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
}
public String toString()
{
return "["+sid+","+sname+","+saddr+"]";
}
}
class Test
{
public static void main(String[] args)
{
Student std1=new Student("S-111", "DD”, "AGR");
Student std2=new Student("S-222", "Anil", "Chennai");
Student std3=new Student("S-333", "Rahul", "Banglore");
Student std4=new Student("S-444", "Rameshh", "Pune");
MyComparator mc=new MyComparator();
TreeSet ts=new TreeSet(mc);
ts.add(std1);
ts.add(std2);
ts.add(std3);
ts.add(std4);
System.out.println(ts);
}
}

Que) In Java applications, if we provide both implicit Sorting through Comparable and
explicit sorting through Comparator to the TreeSet object at a time then which Sorting
logic would be preferred by TreeSet inorder to Sort elements?

If we provide both implicit Sorting through Comparable and Explicit Sorting through Comparator to the TreeSet
object at a time then TreeSet will take explicit Sorting through Comparator to sort all the elements.
EX:
import java.util.*;
class MyComparator implements Comparator
{
public int compare(Object obj1, Object obj2)

{
Customer cust1=(Customer)obj1;
Customer cust2=(Customer)obj2;

int val=cust1.caddr.compareTo(cust2.caddr);
return -val;
}
}
class Customer implements Comparable
{
String cid;
String cname;
String caddr;

Customer(String cid, String cname, String caddr)


{
this.cid=cid;
this.cname=cname;
this.caddr=caddr;
}
public String toString()
{
return "["+cid+","+cname+","+caddr+"]";
}
public int compareTo(Object obj)
{
Customer cust=(Customer)obj;
int val=this.caddr.compareTo(cust.caddr);
return val;
}
}
class Test
{
public static void main(String[] args)
{
Customer c1=new Customer("C-111", "DD", "AGR");
Customer c2=new Customer("C-222", "Anil", "Mathura");
Customer c3=new Customer("C-333", "Rahul", "Banglore");
Customer c4=new Customer("C-444", "Ramesh", "Pune");
MyComparator mc=new MyComparator();
TreeSet ts=new TreeSet(mc);
ts.add(c1);
ts.add(c2);
ts.add(c3);
ts.add(c4);

System.out.println(ts);
}
}

Queue:

• It was introduced in JDK 5.0 version.


• It is a direct child interface to Collection Interface.
• It able to arrange all the elements as per FIFO [First In First Out], but, it is possible to change this
algorithm as per our requirement.
• It able to allow duplicate elements.
• It is not following Insertion order.
• It is following Sorting order.
• It will not allow null values, if we add null value then JVM will rise an Exception like
java.lang.NullPointerException.
• It will not allow heterogeneous elements, if we add heterogeneous elements then JVM will rise
an exception like java.lang.ClassCastException.
• It able to allow only homogeneous elements.
• It able to allow comparable objects bydefault, if we add non comparable objects then JVM will
rise an exception like java.lang.ClassCastException.
• If we want to add non comparable objects then we have to use Comparator.
• It able to manage all elements prior to process.
Methods:
• public void offer(Object obj)

It can be used to insert the specified element to Queue.


• public Object peek()

It can be used to return head element of the Queue.


• public Object element()

It can be used to return head element of the Queue


Note: If we access peek() method on an empty Queue then peek() will return "null" value. If we
access element() method on an empty Queue then element() method will rise an exception like
java.util.NoSuchElementException
• public Object poll()

It can be used to return and remove head element from Queue.


• public Object remove()
It can be used to return and remove head element from Queue.
Note: If we access poll() method on an empty Queue then poll() method will return "null" value.
If we access remove() method on an empty Queue then remove() method will rise an exception
like "java.util.NoSuchElementException".
EX:
1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) PriorityQueue q=new PriorityQueue();
7) q.offer("A");
8) q.offer("B");
9) q.offer("C");
10) q.offer("D");
11) q.offer("E");
12) q.offer("F");
13) System.out.println(q);
14) System.out.println(q.peek());
15) System.out.println(q);
16) System.out.println(q.element());
17) System.out.println(q);
18) /*
19) PriorityQueue q1=new PriorityQueue();
20) System.out.println(q1.peek());--> Null
21) System.out.println(q1.element());--> Exception
22) */
23) System.out.println(q.poll());
24) System.out.println(q);
25) System.out.println(q.remove());
26) System.out.println(q);
27) /*
28) PriorityQueue q1=new PriorityQueue();
29) System.out.println(q1.poll());--> Null
30) System.out.println(q1.remove());-->Exception
31) */
32) }
33) }

PriorityQueue:
• It was introduced in JDK 5.0 version.
• It is not Legacy Collection.
• It is a direct implementation class to Queue interface.

• It able to arrange all the elements prior to processing on the basis of the priorities.
• It able to allow duplicate elements.
• It is not following Insertion order.
• It is following Sorting order.
• It will not allow null values, if we add null value then JVM will rise an Exception like
java.lang.NullPointerException.
• It will not allow heterogeneous elements, if we add heterogeneous elements then JVM will rise
an exception like java.lang.ClassCastException.
• It able to allow only homogeneous elements.
• It able to allow comparable objects by default, if we add non comparable objects then JVM will
rise an exception like java.lang.ClassCastException.
• If we want to add non comparable objects then we have to use Comparator.
• Its initial capacity 11 elements.
• It is not synchronized .
• No method is synchronized in PriorityQueue.
• It allows more than one thread at a time to access data.
• It follows parallel execution.
• It able to reduce application execution time.
• It able to improve application performance.
• It is not giving guarantee for Data consistency.
• It is not threadsafe.

Constructors:
• public PriorityQueue()

It able to create an empty PriorityQueue object


EX: PriorityQueue p = new PriorityQueue();
• public PriorityQueue(int capacity)

It can be used to create an empty Queue with the specified


capacity.
EX: PriorityQueue p = new PriorityQueue(20);
• public PriorityQueue(int capacity,Comparator c)

It able to create an empty PriorityQueue with explicit sorting logic throug COmparator and the
specified capacity.
EX: MyComparator mc = new MyComparator();
PriorityQueue p = new PriorityQueue(20,mc);
• public PriorityQueue(SortedSet ss)

It able to create PriorityQueue object with all the elements of


the specified SortedSet.
EX:
TreeSet ts=new TreeSet();
ts.add("B");
ts.add("E");
ts.add("C");
ts.add("A");
ts.add("D");
System.out.println(ts);
PriorityQueue p = new PriorityQueue(ts);
System.out.println(p);

public PriorityQueue(Collection c)
It able to create PriorityQueue object with all the elements of the specified Collection.
EX:
ArrayList al = new ArrayList();
al.add("A");
al.add("B");
al.add("C");
al.add("D");
System.out.println(al);
PriorityQueue p = new PriorityQueue(al);
System.out.println(p);
EX:
1) import java.util.*;
2) class Test
3) {
4) public static void main(String[] args)
5) {
6) PriorityQueue p=new PriorityQueue();
7) p.add("A");
8) p.add("D");
9) p.add("B");
10) p.add("C");
11) p.add("F");
12) p.add("E");
13) System.out.println(p);
14) p.add("B");
15) System.out.println(p);
16) //p.add(null);-->NullPointerException
17) //p.add(new Integer(10));->ClassCastException
18) //p.add(new StringBuffer("BBB"));->ClassCastException
19) }
20) }

You might also like