0% found this document useful (0 votes)
7 views29 pages

Collections in Java2

The document provides an overview of the Java Collections Framework, which is designed for storing and manipulating groups of objects through various interfaces and classes such as List, Set, and Queue. It details the methods available in the Collection interface, the Iterator interface, and specific implementations like ArrayList and LinkedList, including their characteristics and examples. Additionally, it highlights the differences between List and Set, emphasizing that Lists can contain duplicates while Sets cannot.

Uploaded by

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

Collections in Java2

The document provides an overview of the Java Collections Framework, which is designed for storing and manipulating groups of objects through various interfaces and classes such as List, Set, and Queue. It details the methods available in the Collection interface, the Iterator interface, and specific implementations like ArrayList and LinkedList, including their characteristics and examples. Additionally, it highlights the differences between List and Set, emphasizing that Lists can contain duplicates while Sets cannot.

Uploaded by

rrc48655
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Collections in java

Collections in java is a framework that provides an architecture to store and manipulate the
group of objects.

All the operations that you perform on a data such as searching, sorting, insertion, manipulation,
deletion etc. can be performed by Java Collections.

Java Collection simply means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).

What is Collection in java

Collection represents a single unit of objects i.e. a group.

What is framework in java

 provides readymade architecture.


 represents set of classes and interface.
 is optional.

What is Collection framework

Collection framework represents a unified architecture for storing and manipulating group of
objects. It has:

1. Interfaces and its implementations i.e. classes


2. Algorithm

Hierarchy of Collection Framework

Let us see the hierarchy of collection [Link] [Link] package contains all the classes
and interfaces for Collection framework.
Methods of Collection interface

There are many methods declared in the Collection interface. They are as follows:

No. Method Description

public boolean add(Object


1 is used to insert an element in this collection.
element)

is used to insert the specified collection elements in the


2 public boolean addAll(Collection c)
invoking collection.
public boolean remove(Object
3 is used to delete an element from this collection.
element)

public boolean is used to delete all the elements of specified collection from
4
removeAll(Collection c) the invoking collection.

public boolean retainAll(Collection is used to delete all the elements of invoking collection except
5
c) the specified collection.

6 public int size() return the total number of elements in the collection.

7 public void clear() removes the total no of element from the collection.

public boolean contains(Object


8 is used to search an element.
element)

public boolean
9 is used to search the specified collection in this collection.
containsAll(Collection c)

10 public Iterator iterator() returns an iterator.

11 public Object[] toArray() converts collection into array.

12 public boolean isEmpty() checks if collection is empty.

public boolean equals(Object


13 matches two collection.
element)

14 public int hashCode() returns the hashcode number for collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in forward direction only.

Methods of Iterator interface


There are only three methods in the Iterator interface. They are:

1. public boolean hasNext() it returns true if iterator has more elements.


2. public object next() it returns the element and moves the cursor pointer to the next
element.
3. public void remove() it removes the last elements returned by the iterator. It is rarely
used.

java List Interface


List Interface is the subinterface of [Link] contains methods to insert and delete elements
in index [Link] is a factory of ListIterator interface.

List Interface declaration

1. public interface List<E> extends Collection<E>

Methods of Java List Interface


Method Description

void add(int index,Object It is used to insert element into the invoking list at the index passed in
element) the index.

boolean addAll(int It is used to insert all elements of c into the invoking list at the index
index,Collection c) passed in the index.

It is used to return the object stored at the specified index within the
object get(int index)
invoking collection.

object set(int index,Object It is used to assign element to the location specified by index within the
element) invoking list.

It is used to remove the element at position index from the invoking list
object remove(int index)
and return the deleted element.

ListIterator listIterator() It is used to return an iterator to the start of the invoking list.

ListIterator listIterator(int It is used to return an iterator to the invoking list that begins at the
index) specified index.
Java List Example

1. import [Link].*;
2. public class ListExample{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Amit");
6. [Link]("Vijay");
7. [Link]("Kumar");
8. [Link](1,"Sachin");
9. [Link]("Element at 2nd position: "+[Link](2));
10. for(String s:al){
11. [Link](s);
12. }
13. }
14. }

Output:

Element at 2nd position: Vijay


Amit
Sachin
Vijay
Kumar

Java ListIterator Interface

ListIterator Interface is used to traverse the element in backward and forward direction.

ListIterator Interface declaration

1. public interface ListIterator<E> extends Iterator<E>

Methods of Java ListIterator Interface:


Method Description

This method return true if the list iterator has more elements when traversing the
boolean hasNext()
list in the forward direction.

Object next() This method return the next element in the list and advances the cursor position.

boolean This method return true if this list iterator has more elements when traversing the
hasPrevious() list in the reverse direction.

Object previous() This method return the previous element in the list and moves the cursor position
backwards.

Example of ListIterator Interface

1. import [Link].*;
2. public class TestCollection8{
3. public static void main(String args[]){
4. ArrayList<String> al=new ArrayList<String>();
5. [Link]("Amit");
6. [Link]("Vijay");
7. [Link]("Kumar");
8. [Link](1,"Sachin");
9. [Link]("element at 2nd position: "+[Link](2));
10. ListIterator<String> itr=[Link]();
11. [Link]("traversing elements in forward direction...");
12. while([Link]()){
13. [Link]([Link]());
14. }
15. [Link]("traversing elements in backward direction...");
16. while([Link]()){
17. [Link]([Link]());
18. }
19. }
20. }

Test it Now

Output:

element at 2nd position: Vijay


traversing elements in forward direction...
Amit
Sachin
Vijay
Kumar
traversing elements in backward direction...
Kumar
Vijay
Sachin
Amit

Example of ListIterator Interface: Book

1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class ListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new ArrayList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. [Link](b1);
24. [Link](b2);
25. [Link](b3);
26. //Traversing list
27. for(Book b:list){
28. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
29. }
30. }
31. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Set
A Set is a Collection that cannot contain duplicate elements. The Set interface contains only methods
inherited from Collection and adds the restriction that duplicate elements are prohibited.

The methods declared by Set are summarized in the following table −

[Link]. Method & Description


1 add( )
Adds an object to the collection.
clear( )
2
Removes all objects from the collection.
contains( )
3
Returns true if a specified object is an element within the collection.
isEmpty( )
4
Returns true if the collection has no elements.
iterator( )
5
Returns an Iterator object for the collection, which may be used to retrieve an object.
remove( )
6
Removes a specified object from the collection.
size( )
7
Returns the number of elements in the collection.

Difference between List and Set

List can contain duplicate elements whereas Set contains unique elements only.
Java ArrayList class
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList class
and implements List interface.

The important points about Java ArrayList class are:

 Java ArrayList class can contain duplicate elements.


 Java ArrayList class maintains insertion order.
 Java ArrayList class is non synchronized.
 Java ArrayList allows random access because array works at the index basis.
 In Java ArrayList class, manipulation is slow because a lot of shifting needs to be occurred if any
element is removed from the array list.

Hierarchy of ArrayList class

As shown in above diagram, Java ArrayList class extends AbstractList class which implements
List interface. The List interface extends Collection and Iterable interfaces in hierarchical order.

ArrayList class declaration

Let's see the declaration for [Link] class.

1. public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable


, Serializable

Constructors of Java ArrayList


Constructor Description

ArrayList() It is used to build an empty array list.

It is used to build an array list that is initialized with the elements of the
ArrayList(Collection c)
collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of Java ArrayList


Method Description

void add(int index, Object It is used to insert the specified element at the specified position index in a
element) list.

It is used to append all of the elements in the specified collection to the end
boolean addAll(Collection
of this list, in the order that they are returned by the specified collection's
c)
iterator.
void clear() It is used to remove all of the elements from this list.

It is used to return the index in this list of the last occurrence of the
int lastIndexOf(Object o)
specified element, or -1 if the list does not contain this element.

It is used to return an array containing all of the elements in this list in the
Object[] toArray()
correct order.

It is used to return an array containing all of the elements in this list in the
Object[] toArray(Object[] a)
correct order.

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean addAll(int index, It is used to insert all of the elements in the specified collection into this list,
Collection c) starting at the specified position.

Object clone() It is used to return a shallow copy of an ArrayList.

It is used to return the index in this list of the first occurrence of the
int indexOf(Object o)
specified element, or -1 if the List does not contain this element.

It is used to trim the capacity of this ArrayList instance to be the list's


void trimToSize()
current size.

Java ArrayList Example

1. import [Link].*;
2. class TestCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. [Link]("Ravi");//Adding object in arraylist
6. [Link]("Vijay");
7. [Link]("Ravi");
8. [Link]("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=[Link]();
11. while([Link]()){
12. [Link]([Link]());
13. }
14. }
15. }

output
Ravi
Vijay
Ravi
Ajay

Java LinkedList class

Java LinkedList class uses doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

 Java LinkedList class can contain duplicate elements.


 Java LinkedList class maintains insertion order.
 Java LinkedList class is non synchronized.
 In Java LinkedList class, manipulation is fast because no shifting needs to be occurred.
 Java LinkedList class can be used as list, stack or queue.
Hierarchy of LinkedList class

As shown in above diagram, Java LinkedList class extends AbstractSequentialList class and
implements List and Deque interfaces.

Doubly Linked List

In case of doubly linked list, we can add or remove elements from both side.

LinkedList class declaration

Let's see the declaration for [Link] class.

1. public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Clo


neable, Serializable

Constructors of Java LinkedList


Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection It is used to construct a list containing the elements of the specified collection, in
c) the order they are returned by the collection's iterator.

Methods of Java LinkedList


Method Description

void add(int index, Object It is used to insert the specified element at the specified position index in a
element) list.

void addFirst(Object o) It is used to insert the given element at the beginning of a list.

void addLast(Object o) It is used to append the given element to the end of a list.

int size() It is used to return the number of elements in a list

boolean add(Object o) It is used to append the specified element to the end of a list.

boolean contains(Object o) It is used to return true if the list contains a specified element.
boolean remove(Object o) It is used to remove the first occurence of the specified element in a list.

Object getFirst() It is used to return the first element in a list.

Object getLast() It is used to return the last element in a list.

It is used to return the index in a list of the first occurrence of the specified
int indexOf(Object o)
element, or -1 if the list does not contain any element.

It is used to return the index in a list of the last occurrence of the specified
int lastIndexOf(Object o)
element, or -1 if the list does not contain any element.

Java LinkedList Example

1. import [Link].*;
2. public class TestCollection7{
3. public static void main(String args[]){
4.
5. LinkedList<String> al=new LinkedList<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10.
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }

Test it Now
Output:Ravi
Vijay
Ravi
Ajay

Java LinkedList Example: Book

1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class LinkedListExample {
15. public static void main(String[] args) {
16. //Creating list of Books
17. List<Book> list=new LinkedList<Book>();
18. //Creating Books
19. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
20. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
21. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
22. //Adding Books to list
23. [Link](b1);
24. [Link](b2);
25. [Link](b3);
26. //Traversing list
27. for(Book b:list){
28. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
29. }
30. }
31. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

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

Difference between List and Set

List can contain duplicate elements whereas Set contains unique elements only.

Hierarchy of HashSet class

The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order.

HashSet class declaration

Let's see the declaration for [Link] class.

1. public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Constructors of Java HashSet class:


Constructor Description

HashSet() It is used to construct a default HashSet.

HashSet(Collection
It is used to initialize the hash set by using the elements of the collection c.
c)

HashSet(int It is used to initialize the capacity of the hash set to the given integer value
capacity) capacity. The capacity grows automatically as elements are added to the HashSet.

Methods of Java HashSet class:


Method Description

void clear() It is used to remove all of the elements from this set.
boolean contains(Object
It is used to return true if this set contains the specified element.
o)

boolean add(Object o) It is used to adds the specified element to this set if it is not already present.

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

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

It is used to return a shallow copy of this HashSet instance: the elements


Object clone()
themselves are not cloned.

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

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

Java HashSet Example

1. import [Link].*;
2. class TestCollection9{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10. //Traversing elements
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }

Test it Now
Ajay
Vijay
Ravi

Java HashSet Example: Book

Let's see a HashSet example where we are adding books to set and printing all the books.
1. import [Link].*;
2. class Book {
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. }
14. public class HashSetExample {
15. public static void main(String[] args) {
16. HashSet<Book> set=new HashSet<Book>();
17. //Creating Books
18. Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
19. Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
20. Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
21. //Adding Books to HashSet
22. [Link](b1);
23. [Link](b2);
24. [Link](b3);
25. //Traversing HashSet
26. for(Book b:set){
27. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
28. }
29. }
30. }

Output:

101 Let us C Yashwant Kanetkar BPB 8


102 Data Communications & Networking Forouzan Mc Graw Hill 4
103 Operating System Galvin Wiley 6

Java TreeSet class


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

 Java TreeSet class contains unique elements only like HashSet.


 Java TreeSet class access and retrieval times are quite fast.
 Java TreeSet class doesn't allow null elements.
 Java TreeSet class is non-synchronized.
 Java TreeSet class maintains ascending order.
 The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.

1. TreeSet treeSet = new TreeSet();


2. Set syncrSet = [Link](treeSet);
Hierarchy of TreeSet class

As shown in the above diagram, the Java TreeSet class implements the NavigableSet interface.
The NavigableSet interface extends SortedSet, Set, Collection and Iterable interfaces in
hierarchical order.

TreeSet Class Declaration

Let's see the declaration for [Link] class.

1. public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializ


able

Constructors of Java TreeSet Class


Constructor Description

It is used to construct an empty tree set that will be sorted in


TreeSet()
ascending order according to the natural order of the tree set.

It is used to build a new tree set that contains the elements of the
TreeSet(Collection<? extends E> c)
collection c.

TreeSet(Comparator<? super E> It is used to construct an empty tree set that will be sorted according
comparator) to given comparator.

It is used to build a TreeSet that contains the elements of the given


TreeSet(SortedSet<E> s)
SortedSet.

Methods of Java TreeSet Class


Method Description

It is used to add the specified element to this set if it


boolean add(E e)
is not already present.

It is used to add all of the elements in the specified


boolean addAll(Collection<? extends E> c)
collection to this set.
It returns the equal or closest greatest element of the
E ceiling(E e) specified element from the set, or null there is no
such element.

It returns a comparator that arranges elements in


Comparator<? super E> comparator()
order.

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

NavigableSet descendingSet() It returns the elements in reverse order.

It returns the equal or closest least element of the


E floor(E e) specified element from the set, or null there is no
such element.

It returns the group of elements that are less than the


SortedSet headSet(E toElement)
specified element.

NavigableSet headSet(E toElement, boolean It returns the group of elements that are less than or
inclusive) equal to(if, inclusive is true) the specified element.

It returns the closest greatest element of the specified


E higher(E e) element from the set, or null there is no such
element.

Iterator iterator() It is used to iterate the elements in ascending order.

It returns the closest least element of the specified


E lower(E e) element from the set, or null there is no such
element.

It is used to retrieve and remove the lowest(first)


E pollFirst()
element.

It is used to retrieve and remove the highest(last)


E pollLast()
element.

It is used to create a late-binding and fail-fast


Spliterator spliterator()
spliterator over the elements.

NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range.

SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.

It returns a set of elements that are greater than or


SortedSet tailSet(E fromElement)
equal to the specified element.

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

It returns true if this set contains the specified


boolean contains(Object o)
element.

boolean isEmpty() It returns true if this set contains no elements.

It is used to remove the specified element from this


boolean remove(Object o)
set if it is present.

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

Object clone() It returns a shallow copy of this TreeSet instance.

It returns the first (lowest) element currently in this


E first()
sorted set.

It returns the last (highest) element currently in this


E last()
sorted set.

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

Java TreeSet Examples

Java TreeSet Example 1:

Let's see a simple example of Java TreeSet.

FileName: [Link]

1. import [Link].*;
2. class TreeSet1{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> al=new TreeSet<String>();
6. [Link]("Ravi");
7. [Link]("Vijay");
8. [Link]("Ravi");
9. [Link]("Ajay");
10. //Traversing elements
11. Iterator<String> itr=[Link]();
12. while([Link]()){
13. [Link]([Link]());
14. }
15. }
16. }

Test it Now

Output:

Ajay
Ravi
Vijay

Java TreeSet Example 2:

Let's see an example of traversing elements in descending order.

FileName: [Link]

1. import [Link].*;
2. class TreeSet2{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. [Link]("Ravi");
6. [Link]("Vijay");
7. [Link]("Ajay");
8. [Link]("Traversing element through Iterator in descending order");
9. Iterator i=[Link]();
10. while([Link]())
11. {
12. [Link]([Link]());
13. }
14.
15. }
16. }

Test it Now

Output:

Traversing element through Iterator in descending order


Vijay
Ravi
Ajay
Traversing element through NavigableSet in descending order
Vijay
Ravi
Ajay

Java TreeSet Example 3:

Let's see an example to retrieve and remove the highest and lowest Value.

FileName: [Link]

1. import [Link].*;
2. class TreeSet3{
3. public static void main(String args[]){
4. TreeSet<Integer> set=new TreeSet<Integer>();
5. [Link](24);
6. [Link](66);
7. [Link](12);
8. [Link](15);
9. [Link]("Lowest Value: "+[Link]());
10. [Link]("Highest Value: "+[Link]());
11. }
12. }

Output:
Lowest Value: 12
Highest Value: 66

Java TreeSet Example 4:

In this example, we perform various NavigableSet operations.

FileName: [Link]

1. import [Link].*;
2. class TreeSet4{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. [Link]("A");
6. [Link]("B");
7. [Link]("C");
8. [Link]("D");
9. [Link]("E");
10. [Link]("Initial Set: "+set);
11.
12. [Link]("Reverse Set: "+[Link]());
13.
14. [Link]("Head Set: "+[Link]("C", true));
15.
16. [Link]("SubSet: "+[Link]("A", false, "E", true));
17.
18. [Link]("TailSet: "+[Link]("C", false));
19. }
20. }

Output:

Initial Set: [A, B, C, D, E]


Reverse Set: [E, D, C, B, A]
Head Set: [A, B, C]
SubSet: [B, C, D, E]
TailSet: [D, E]

Java TreeSet Example 5:

In this example, we perform various SortedSetSet operations.


FileName: [Link]

1. import [Link].*;
2. class TreeSet5{
3. public static void main(String args[]){
4. TreeSet<String> set=new TreeSet<String>();
5. [Link]("A");
6. [Link]("B");
7. [Link]("C");
8. [Link]("D");
9. [Link]("E");
10.
11. [Link]("Intial Set: "+set);
12.
13. [Link]("Head Set: "+[Link]("C"));
14.
15. [Link]("SubSet: "+[Link]("A", "E"));
16.
17. [Link]("TailSet: "+[Link]("C"));
18. }
19. }

Output:

Intial Set: [A, B, C, D, E]


Head Set: [A, B]
SubSet: [A, B, C, D]
TailSet: [C, D, E]

Java TreeSet Example: Book

Let's see a TreeSet example where we are adding books to the set and printing all the books. The
elements in TreeSet must be of a Comparable type. String and Wrapper classes are Comparable
by default. To add user-defined objects in TreeSet, you need to implement the Comparable
interface.

FileName: [Link]
1. import [Link].*;
2. class Book implements Comparable<Book>{
3. int id;
4. String name,author,publisher;
5. int quantity;
6. public Book(int id, String name, String author, String publisher, int quantity) {
7. [Link] = id;
8. [Link] = name;
9. [Link] = author;
10. [Link] = publisher;
11. [Link] = quantity;
12. }
13. // implementing the abstract method
14. public int compareTo(Book b) {
15. if(id>[Link]){
16. return 1;
17. }else if(id<[Link]){
18. return -1;
19. }else{
20. return 0;
21. }
22. }
23. }
24. public class TreeSetExample {
25. public static void main(String[] args) {
26. Set<Book> set=new TreeSet<Book>();
27. //Creating Books
28. Book b1=new Book(121,"Let us C","Yashwant Kanetkar","BPB",8);
29. Book b2=new Book(233,"Operating System","Galvin","Wiley",6);
30. Book b3=new Book(101,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);

31. //Adding Books to TreeSet


32. [Link](b1);
33. [Link](b2);
34. [Link](b3);
35. //Traversing TreeSet
36. for(Book b:set){
37. [Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]+" "+[Link]);
38. }
39. }
40. }
Output:

101 Data Communications & Networking Forouzan Mc Graw Hill 4


121 Let us C Yashwant Kanetkar BPB 8
233 Operating System Galvin Wiley 6

ClassCast Exception in TreeSet

If we add an object of the class that is not implementing the Comparable interface, the ClassCast
Exception is raised. Observe the following program.

FileName: [Link]

1. // important import statement


2. import [Link].*;
3.
4. class Employee
5. {
6.
7. int empId;
8. String name;
9.
10. // getting the name of the employee
11. String getName()
12. {
13. return [Link];
14. }
15.
16. // setting the name of the employee
17. void setName(String name)
18. {
19. [Link] = name;
20. }
21.
22. // setting the employee id
23. // of the employee
24. void setId(int a)
25. {
26. [Link] = a;
27. }
28.
29. // retrieving the employee id of
30. // the employee
31. int getId()
32. {
33. return [Link];
34. }
35.
36. }
37.
38. public class ClassCastExceptionTreeSet
39. {
40.
41. // main method
42. public static void main(String[] argvs)
43. {
44. // creating objects of the class Employee
45. Employee obj1 = new Employee();
46.
47. Employee obj2 = new Employee();
48.
49. TreeSet<Employee> ts = new TreeSet<Employee>();
50.
51. // adding the employee objects to
52. // the TreeSet class
53. [Link](obj1);
54. [Link](obj2);
55.
56. [Link]("The program has been executed successfully.");
57.
58. }
59. }

You might also like