0% found this document useful (0 votes)
1 views30 pages

7 Java-Collections-Framework 2 (HashSet)

The document provides an overview of the Java Collections Framework, specifically focusing on the Set interface and its implementations, HashSet and TreeSet. It outlines the characteristics, methods, and examples of both classes, highlighting their differences and usage in storing unique elements. The document also emphasizes the importance of implementing equals() and hashCode() methods for user-defined objects in HashSet and the Comparable interface for TreeSet to maintain order.

Uploaded by

leba chinh
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)
1 views30 pages

7 Java-Collections-Framework 2 (HashSet)

The document provides an overview of the Java Collections Framework, specifically focusing on the Set interface and its implementations, HashSet and TreeSet. It outlines the characteristics, methods, and examples of both classes, highlighting their differences and usage in storing unique elements. The document also emphasizes the importance of implementing equals() and hashCode() methods for user-defined objects in HashSet and the Comparable interface for TreeSet to maintain order.

Uploaded by

leba chinh
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

JAVA

COLLECTIONS FRAMEWORK
Set Interface

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use


Agenda
• Set Interface Overview
1

• HashSet Class
2

• TreeSet Class
3

• Q&A
4

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 2


Lesson Objectives
 Understand the characteristics of HashSet and TreeSet.
 Understand the difference between Set and other collection types.
 Perform common operations such as adding, removing, and accessing elements
in an HashSet.
 Perform common operations such as adding, removing, and accessing elements
in an TreeSet.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 3


Section 4

Set Interface

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 4


Hierarchy of Collections Framework - review

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 5


Set Interface
 Set interface in Java is present in [Link] package.
 It extends the Collection interface.

 It represents the unordered set of elements which doesn't allow us to store the duplicate items.

 We can store at most one null value in Set.

 Set is implemented by HashSet, LinkedHashSet, and TreeSet.

 Set can be instantiated as:


Set<data-type> s1 = new HashSet<data-type>();
Set<data-type> s2 = new LinkedHashSet<data-type>();
Set<data-type> s3 = new TreeSet<data-type>();

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 6


Section 2

HashSet class

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 7


HashSet class
 Java HashSet class is used to create a collection that uses a hash table for storage.

 It inherits the AbstractSet class and implements Set interface.

 The important points about Java HashSet class are:

 HashSet stores the elements by using a mechanism called hashing.

 HashSet contains unique elements only.

 HashSet allows null value.

 HashSet class is non synchronized.

 HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.

 HashSet is the best approach for search operations.

 The initial default capacity of HashSet is 16, and the load factor is 0.75.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 8


Methods of Java HashSet class
Method Description
boolean add(E e) It is used to add the specified element to this set if it is not already present.

void clear() It is used to remove all of the elements from the set.

object clone() It is used to return a shallow copy of this HashSet instance: the elements themselves are not
cloned.
boolean contains(Object o) It is used to return true if this set contains the specified element.

boolean isEmpty() It is used to return true if this set contains no elements.

Iterator<E> iterator() It is used to return an iterator over the elements in this set.

boolean remove(Object o) It is used to remove the specified element from this set if it is present.

int size() It is used to return the number of elements in the set.

Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the set.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 9


HashSet Example
public class HashSetTest { Output:
public static void main(String[] args) { Five
One
// Creating HashSet and adding elements
HashSet<String> set = new HashSet<>(); Four
[Link]("One"); Two
[Link]("Two");
[Link]("Three"); Three
[Link]("Three"); // ignoring duplicate elements
[Link]("Four");
[Link]("Five");
Iterator<String> i = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 10


Store user-defined class objects
 Give Course class:
public class Course {
private String courseCode;
private String courseTitle;
private int numOfCredits;

public Course() {

public Course(String courseCode, String courseTitle, int numOfCredits) {


super();
[Link] = courseCode;
[Link] = courseTitle;
[Link] = numOfCredits;
}
// getter, setter methods
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 11


Store user-defined class objects
 Consider the following snippet code:
public class HashSetDemo {

public static void main(String[] args) {


HashSet<Course> courses = new HashSet<>();

Course c1 = new Course("J001", "Java SE Programming Essentials", 10);


Course c2 = new Course("S004", "SQL", 5);
Course c3 = new Course("F003", "Front End Essentials", 10);
Course c4 = new Course("S004", "SQL", 5);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);

[Link]("Size of set: " + [Link]());

}
}

Output: Why? c2 and c4 are the same values.


Size of set: 4 Set doesn't allow us to store the duplicate items.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 12
Working of HashSet in Java
 HashSet uses hashing algorithms to store, remove, and retrieve its elements.

 When an object is added to the Set, its hash code is used to choose a “bucket” into which to
place the object.

 Example: [Link] (123);

 For every element in a hash set, the hash is computed and


elements with the same hash are grouped together. This
group of similar hashes is called a bucket and they are
usually stored as linked lists.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 13


Working of HashSet in Java
 If have same hashcode then the equals() method will be called.
 return true: the call leaves the set unchanged and returns false.
 Return false: grouped together of similar hashes is called a bucket and they are usually stored
as linked lists.
 Example, if we want to insert 88 in the following hash set:
 We compute the hash of 88 which is 8, and we insert it to the end of the bucket with hash 8.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 14


equals() and hashCode()
 Modify Course class, you must overriding equals() and hashCode() methods:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((courseCode == null) ? 0 : [Link]());
result = prime * result + ((courseTitle == null) ? 0 : [Link]());
result = prime * result + numOfCredits;
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Course other = (Course) obj;
return [Link](courseCode, [Link])
&& [Link](courseTitle, [Link])
&& numOfCredits == [Link];
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 15


Review Result
 Consider the following snippet code:
public class HashSetDemo {

public static void main(String[] args) {


HashSet<Course> courses = new HashSet<>();

Course c1 = new Course("J001", "Java SE Programming Essentials", 10);


Course c2 = new Course("S004", "SQL", 5);
Course c3 = new Course("F003", "Front End Essentials", 10);
Course c4 = new Course("S004", "SQL", 5);
[Link](c1);
[Link](c2);
[Link](c3);
[Link](c4);

[Link]("Size of set: " + [Link]());

}
}

Output: Has only 1 element with value ("S004", "SQL", 5) in HastSet


Size of set: 3
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 16
HashSet
 Demo!

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 17


Section 3

TreeSet class

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 18


TreeSet
 Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet
class and implements the NavigableSet interface. The objects of the TreeSet class are stored in
ascending order.
 The important points about Java TreeSet class are:
 Java TreeSet class contains unique elements only like HashSet.
 Java TreeSet class access and retrieval times are quiet fast.
 Java TreeSet class doesn't allow null element.
 Java TreeSet class is non synchronized.
 Java TreeSet class maintains ascending order.
 Constructors:
Constructor Description
TreeSet() It is used to construct an empty tree set that will be sorted in ascending order according to
the natural order of the tree set.
TreeSet(Collection<? extends E> c) It is used to build a new tree set that contains the elements of the collection c.
TreeSet(Comparator<? super E> It is used to construct an empty tree set that will be sorted according to given comparator.
comparator)
TreeSet(SortedSet<E> s) It is used to build a TreeSet that contains the elements of the given SortedSet.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 19


Methods of Java TreeSet class
Method Description
boolean add(E e) It is used to add the specified element to this set if it is not already present.

boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified collection to this set.

E ceiling(E e) It returns the equal or closest greatest element of the specified element from the
set, or null there is no such element.

Iterator descendingIterator() It is used iterate the elements in descending order.


NavigableSet descendingSet() It returns the elements in reverse order.
E floor(E e) It returns the equal or closest least element of the specified element from the set,
or null there is no such element.

SortedSet headSet(E toElement) It returns the group of elements that are less than the specified element.

NavigableSet headSet(E toElement, It returns the group of elements that are less than or equal to(if, inclusive is true)
boolean inclusive) the specified element.
E higher(E e) It returns the closest greatest element of the specified element from the set, or
null there is no such element.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 20


Methods of Java TreeSet class
Method Description
E lower(E e) It returns the closest least element of the specified element from the set, or null there
is no such element.
E pollFirst() It is used to retrieve and remove the lowest(first) element.

E pollLast() It is used to retrieve and remove the highest(last) element.

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or equal to the specified element.

NavigableSet tailSet(E fromElement, It returns a set of elements that are greater than or equal to (if, inclusive is true) the
boolean inclusive) specified element.
E first() It returns the first (lowest) element currently in this sorted set.

E last() It returns the last (highest) element currently in this sorted set.

int size() It returns the number of elements in this set.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 21


TreeSet Example
public class TreeSetTest { Output:
public static void main(String[] args) { Ajay
// Creating and adding elements
Ravi
TreeSet<String> al = new TreeSet<String>();
Vijay
[Link]("Ravi");
[Link]("Vijay");
[Link]("Ravi"); String and Integer both implement the Comparable
[Link]("Ajay"); interface in Java!
// Traversing elements
Iterator<String> itr = [Link]();
while ([Link]()) {
[Link]([Link]());
}
}
}

By default, the objects or elements of the TreeSet are stored according to the natural ordering
in ascending order.
09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 22
TreeSet Example
public class TreeSetTest2 { Output:
Initial Set: [12, 15, 24, 66]
public static void main(String[] args) { Reverse Set: [66, 24, 15, 12]
TreeSet<Integer> set = new TreeSet<Integer>();
Highest Value: 12
[Link](24);
Lowest Value: 66
[Link](66);
[Link](12);
[Link](15);
[Link]("Initial Set: " + set);

[Link]("Reverse Set: " + [Link]());

[Link]("Highest Value: " + [Link]());


[Link]("Lowest Value: " + [Link]());
}
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use 23


Java TreeSet Example: Course class
 Let's see a TreeSet example where we are adding courses to the set and printing all the courses.
 String and Wrapper classes are Comparable by default
 To add user-defined objects in TreeSet, you need to implement the Comparable interface.
public class Course implements Comparable<Course> {
private String courseCode;
private String courseTitle;
private int numOfCredits;

public Course() {

public Course(String courseCode, String courseTitle, int numOfCredits) {


super();
[Link] = courseCode;
[Link] = courseTitle;
[Link] = numOfCredits;
}
// getter, setter methods
@Override
public int compareTo(Course c) {
return [Link] - [Link];
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 24


Java TreeSet Example: Course class
public class TreeSetExample { Output:
public static void main(String[] args) {
Set<Course> courses = new TreeSet<>(); Course [courseCode=0223, courseTitle=HTML, numOfCredits=3]
Course course1 = new Course("1122", "Java", 10); Course [courseCode=2345, courseTitle=SQL, numOfCredits=5]
Course course2 = new Course("3233", "Python", 8);
Course [courseCode=0233, courseTitle=C#, numOfCredits=6]
Course course3 = new Course("2345", "SQL", 5);
Course [courseCode=3233, courseTitle=Python, numOfCredits=8]
Course course4 = new Course("0223", "HTML", 3);
Course course5 = new Course("0233", "C#", 6); Course [courseCode=1122, courseTitle=Java, numOfCredits=10]
[Link](course1);
[Link](course2);
[Link](course3);
[Link](course4);
[Link](course5);
// Traversing elements If we add an object of the class that is not implementing the
Iterator<Course> itr = [Link](); Comparable interface, the ClassCastException is raised.
while ([Link]()) {
[Link]([Link]());
}
}
}

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 25


TreeSet Comparator
 The TitleComparator class implements the Comparator interface.
public class TitleComparator implements Comparator<Course> {
@Override
public int compare(Course c1, Course c2) {
return [Link]().compareTo([Link]());
}
}

 Create TreeSet with Comparator:


Set<Course> courses = new TreeSet<>(new NameComparator());

 Output:
Course [courseCode=0233, courseTitle=C#, numOfCredits=6]
Course [courseCode=0223, courseTitle=HTML, numOfCredits=3]
Course [courseCode=1122, courseTitle=Java, numOfCredits=10]
Course [courseCode=3233, courseTitle=Python, numOfCredits=8]
Course [courseCode=2345, courseTitle=SQL, numOfCredits=5]

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 26


Difference between Hashset and Treeset in Java
Parameters HashSet TreeSet

Ordering or Sorting It does not provide a guarantee to sort the data. It provides a guarantee to sort the data. The sorting depends
on the supplied Comparator.

Null Objects In HashSet, only an element can be null. It does not allow null elements.

Comparison It uses hashCode() or equals() method for comparison. It uses compare() or compareTo() method for comparison.

Performance It is faster than TreeSet. It is slower in comparison to HashSet.

Implementation Internally it uses HashMap to store its elements. Internally it uses TreeMap to store its elements.

Data Structure HashSet is backed up by a hash table. TreeSet is backed up by a Red-black Tree.

Values Stored It allows only heterogeneous values. It allows only homogeneous values.

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 27


TreeSet
 Demo!

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 28


Agenda
1 Set Interface Overview

2 HashSet Class

3 TreeSet Class

4 Q&A

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Acadademy - Internal Use 29


THANK YOU!

09e-BM/DT/FSOFT - @FPT SOFTWARE - FPT Software Academy - Internal Use

You might also like