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

Collection-1

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects. It covers various interfaces like Collection, List, and ArrayList, including their methods for adding, removing, and accessing elements. Additionally, it explains the differences between non-generic and generic collections, along with examples of iterating through collections and managing size and capacity.

Uploaded by

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

Collection-1

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects. It covers various interfaces like Collection, List, and ArrayList, including their methods for adding, removing, and accessing elements. Additionally, it explains the differences between non-generic and generic collections, along with examples of iterating through collections and managing size and capacity.

Uploaded by

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

The Collection in Java is a framework that provides an architecture to store and manipulate

the group of objects.

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

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

No. Method Description


1 public boolean add(E e) It is used to insert an element in this

collection.

2 public boolean It is used to insert the specified collection

addAll(Collection<? extends elements in the invoking collection.

E> c)

3 public boolean It is used to delete an element from the

remove(Object element) collection.

4 public boolean It is used to delete all the elements of the

removeAll(Collection<?> c) specified collection from the invoking

collection.

5 default boolean It is used to delete all the elements of the

removeIf(Predicate<? super collection that satisfy the specified predicate.

E> filter)

6 public boolean It is used to delete all the elements of invoking

retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in the

collection.

8 public void clear() It removes the total number of elements from

the collection.

9 public boolean It is used to search an element.

contains(Object element)
10 public boolean It is used to search the specified collection in

containsAll(Collection<?> c) the collection.

11 public Iterator iterator() It returns an iterator.

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

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the

runtime type of the returned array is that of the

specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with the

parallelStream() collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with the

collection as its source.

17 default Spliterator<E> It generates a Spliterator over the specified

spliterator() elements in the collection.

18 public boolean equals(Object It matches two collections.

element)

19 int hashCode() It returns the hash code number of the

collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction

only.

Methods of Iterator interface

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

N Method Description
o.

1 public boolean It returns true if the iterator has more elements otherwise

hasNext() it returns false.

2 public Object next() It returns the element and moves the cursor pointer to the

next element.

3 public void It removes the last elements returned by the iterator. It is

remove() less used.

Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.

ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.

package com.flm;
import java.util.*;
class ArrayListDemo {
public static void main(String args[]) {
ArrayList<String> list = new ArrayList<String>();// Creating arraylist
list.add("Ravi");// Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr = list.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

ArrayList

Java ArrayList class uses a dynamic array for storing the elements. It is like an array, but
there is no size limit. We can add or remove elements anytime. So, it is much more flexible
than the traditional array. It is found in the java.util package. It is like the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List interface
so we can use all the methods of the List interface here. The ArrayList maintains the
insertion order internally.

It inherits the AbstractList class and implements List interface.

The important points about the Java ArrayList class are:

○ Java ArrayList class can contain duplicate elements.


○ Java ArrayList class maintains insertion order.

○ Java ArrayList class is non synchronized.

○ In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a
lot of shifting needs to occur if any element is removed from the array list.

○ We can not create an array list of the primitive types, such as int, float, char, etc. It is
required to use the required wrapper class in such cases. For example:

1. ArrayList<int> al = ArrayList<int>(); // does not work


2. ArrayList<Integer> al = new ArrayList<Integer>(); // works fine

○ Java ArrayList gets initialized by the size. The size is dynamic in the array list, which
varies according to the elements getting added or removed from the list

Constructors of ArrayList

onstructor Description

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

ayList(Collection<? extends E> c) It is used to build an array list that is initialized with the elements of the

collection c.

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

Method Description

void add(int index, E It is used to insert the specified element at the specified

element) position in a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean addAll(int It is used to append all the elements in the specified

index, Collection<? collection, starting at the specified position of the list.

extends E> c)

void clear() It is used to remove all of the elements from this list.
void It is used to enhance the capacity of an ArrayList instance.

ensureCapacity(int

requiredCapacity)

E get(int index) It is used to fetch the element from the particular position of

the list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

Iterator()

listIterator()

int It is used to return the index in this list of the last occurrence

lastIndexOf(Object of the specified element, or -1 if the list does not contain this

o) element.

Object[] toArray() It is used to return an array containing all of the elements in

this list in the correct order.


<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in

this list in the correct order.

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

boolean It returns true if the list contains the specified element.

contains(Object o)

int indexOf(Object o) It is used to return the index in this list of the first occurrence

of the specified element, or -1 if the List does not contain this

element.

E remove(int index) It is used to remove the element present at the specified

position in the list.

boolean It is used to remove the first occurrence of the specified

remove(Object o) element.
boolean It is used to remove all the elements from the list.

removeAll(Collection

<?> c)

boolean It is used to remove all the elements from the list that satisfies

removeIf(Predicate< the given predicate.

? super E> filter)

protected void It is used to remove all the elements lies within the given

removeRange(int range.

fromIndex, int

toIndex)

void It is used to replace all the elements from the list with the

replaceAll(UnaryOpe specified element.

rator<E> operator)

void It is used to retain all the elements in the list that are present

retainAll(Collection< in the specified collection.

?> c)
E set(int index, E It is used to replace the specified element in the list, present at

element) the specified position.

void It is used to sort the elements of the list on the basis of the

sort(Comparator<? specified comparator.

super E> c)

Spliterator<E> It is used to create a spliterator over the elements in a list.

spliterator()

List<E> subList(int It is used to fetch all the elements that lies within the given

fromIndex, int range.

toIndex)

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

void trimToSize() It is used to trim the capacity of this ArrayList instance to be

the list's current size.


Java Non-generic Vs. Generic Collection

Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it
is type-safe, so typecasting is not required at runtime.

Let's see the old non-generic example of creating a Java collection.

1. ArrayList list=new ArrayList();//creating old non-generic arraylist

Let's see the new generic example of creating java collection.

1. ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist

In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have
the only specified type of object in it. If you try to add another type of object, it gives a
compile-time error.

import java.util.*;

public class ArrayListExample1{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Printing the arraylist object


System.out.println(list);

Iterating ArrayList using Iterator

import java.util.*;

public class ArrayListExample2{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through Iterator

Iterator itr=list.iterator();//getting the Iterator

while(itr.hasNext()){//check if iterator has the elements

System.out.println(itr.next());//printing the element and move to next

Iterating ArrayList using For-each loop


Let's see an example to traverse the ArrayList elements using the for-each loop

FileName: ArrayListExample3.java

import java.util.*;

public class ArrayListExample3{

public static void main(String args[]){

ArrayList<String> list=new ArrayList<String>();//Creating arraylist

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Traversing list through for-each loop

for(String fruit:list)

System.out.println(fruit);

Get and Set ArrayList


The get() method returns the element at the specified index, whereas the set() method
changes the element.

How to Sort ArrayList

The java.util package provides a utility class Collections, which has the static method sort().
Using the Collections.sort() method, we can easily sort the ArrayList.

import java.util.*;

class SortArrayList{

public static void main(String args[]){

//Creating a list of fruits

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

list1.add("Mango");

list1.add("Apple");

list1.add("Banana");

list1.add("Grapes");

//Sorting the list

Collections.sort(list1);

//Traversing list through the for-each loop

for(String fruit:list1)

System.out.println(fruit);

System.out.println("Sorting numbers...");
//Creating a list of numbers

List<Integer> list2=new ArrayList<Integer>();

list2.add(21);

list2.add(11);

list2.add(51);

list2.add(1);

//Sorting the list

Collections.sort(list2);

//Traversing list through the for-each loop

for(Integer number:list2)

System.out.println(number);

Ways to iterate the elements of the collection in Java

There are various ways to traverse the collection elements:

1. By Iterator interface.

2. By for-each loop.

3. By ListIterator interface.

4. By for loop.

User-defined class objects in Java ArrayList


Let's see an example where we are storing Student class object in an array list.

class Student{

int rollno;

String name;

int age;

Student(int rollno,String name,int age){

this.rollno=rollno;

this.name=name;

this.age=age;

—--------

import java.util.*;

class ArrayList5{

public static void main(String args[]){

//Creating user-defined class objects

Student s1=new Student(101,"Sonoo",23);

Student s2=new Student(102,"Ravi",21);

Student s2=new Student(103,"Hanumat",25);


//creating arraylist

ArrayList<Student> al=new ArrayList<Student>();

al.add(s1);//adding Student class object

al.add(s2);

al.add(s3);

//Getting Iterator

Iterator itr=al.iterator();

//traversing elements of ArrayList object

while(itr.hasNext()){

Student st=(Student)itr.next();

System.out.println(st.rollno+" "+st.name+" "+st.age);

Size and Capacity of an ArrayList

Size and capacity of an array list are the two terms that beginners find confusing. Let's
understand it in this section with the help of some examples. Consider the following code
snippet.

FileName: SizeCapacity.java
import java.util.*;

public class SizeCapacity

public static void main(String[] args) throws Exception

ArrayList<Integer> al = new ArrayList<Integer>();

System.out.println("The size of the array is: " + al.size());

Output:

The size of the array is: 0

Explanation: The output makes sense as we have not done anything with the array list. Now
observe the following program.

import java.util.*;

public class SizeCapacity1


{

public static void main(String[] args) throws Exception

ArrayList<Integer> al = new ArrayList<Integer>(10);

System.out.println("The size of the array is: " + al.size());

Output:

The size of the array is: 0

Explanation: We see that the size is still 0, and the reason behind this is the number 10
represents the capacity not the size. In fact, the size represents the total number of
elements present in the array. As we have not added any element, therefore, the size of the
array list is zero in both programs.

Capacity represents the total number of elements the array list can contain. Therefore, the
capacity of an array list is always greater than or equal to the size of the array list. When we
add an element to the array list, it checks whether the size of the array list has become equal
to the capacity or not. If yes, then the capacity of the array list increases. So, in the above
example, the capacity will be 10 till 10 elements are added to the list. When we add the 11th
element, the capacity increases. Note that in both examples, the capacity of the array list is
10. In the first case, the capacity is 10 because the default capacity of the array list is 10. In
the second case, we have explicitly mentioned that the capacity of the array list is 10.
LinkedList class

Java LinkedList class uses a 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 occur.


○ Java LinkedList class can be used as a list, stack or queue.

Hierarchy of LinkedList class

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

Doubly Linked List

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

Constructors of Java LinkedList

Constructor Description

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

LinkedList(Collec It is used to construct a list containing the elements of the

tion<? extends specified collection, in the order, they are returned by the

E> c) collection's iterator.


Methods of Java LinkedList

Method Description

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

void add(int index, It is used to insert the specified element at the specified

E element) position index in a list.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean It is used to append all of the elements in the specified

addAll(Collection<? collection to the end of this list, in the order that they are

extends E> c) returned by the specified collection's iterator.

boolean addAll(int It is used to append all the elements in the specified collection,

index, Collection<? starting at the specified position of the list.

extends E> c)
void addFirst(E e) It is used to insert the given element at the beginning of a list.

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

void clear() It is used to remove all the elements from a list.

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

boolean It is used to return true if a list contains a specified element.

contains(Object o)

Iterator<E> It is used to return an iterator over the elements in a deque in

descendingIterator( reverse sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position in a list.
E getFirst() It is used to return the first element in a list.

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

int indexOf(Object It is used to return the index in a list of the first occurrence of

o) the specified element, or -1 if the list does not contain any

element.

int It is used to return the index in a list of the last occurrence of

lastIndexOf(Object the specified element, or -1 if the list does not contain any

o) element.

ListIterator<E> It is used to return a list-iterator of the elements in proper

listIterator(int sequence, starting at the specified position in the list.

index)

boolean offer(E e) It adds the specified element as the last element of a list.
boolean offerFirst(E It inserts the specified element at the front of a list.

e)

boolean offerLast(E It inserts the specified element at the end of a list.

e)

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a list is

empty.

E peekLast() It retrieves the last element of a list or returns null if a list is

empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or returns

null if a list is empty.


E pollLast() It retrieves and removes the last element of a list, or returns null

if a list is empty.

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a list.

E remove() It is used to retrieve and removes the first element of a list.

E remove(int index) It is used to remove the element at the specified position in a

list.

boolean It is used to remove the first occurrence of the specified

remove(Object o) element in a list.

E removeFirst() It removes and returns the first element from a list.


boolean It is used to remove the first occurrence of the specified

removeFirstOccurre element in a list (when traversing the list from head to tail).

nce(Object o)

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in a list

removeLastOccurre (when traversing the list from head to tail).

nce(Object o)

E set(int index, E It replaces the element at the specified position in a list with

element) the specified element.

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

in proper sequence (from first to the last element).

<T> T[] toArray(T[] It returns an array containing all the elements in the proper

a) sequence (from first to the last element); the runtime type of

the returned array is that of the specified array.


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

Java LinkedList Example


import java.util.*;

public class LinkedList1{

public static void main(String args[]){

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

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

}
}

Difference Between ArrayList and LinkedList


ArrayList and LinkedList both implement the List interface and maintain insertion order. Both
are non-synchronized classes.

However, there are many differences between the ArrayList and LinkedList classes that are
given below.

ArrayList LinkedList

1) ArrayList internally uses a dynamic array to LinkedList internally uses a doubly

store the elements. linked list to store the elements.

2) Manipulation with ArrayList is slow Manipulation with LinkedList is

because it internally uses an array. If any faster than ArrayList because it uses

element is removed from the array, all the a doubly linked list, so no bit shifting

other elements are shifted in memory. is required in memory.

3) An ArrayList class can act as a list only LinkedList class can act as a list and

because it implements List only. queue both because it implements

List and Deque interfaces.


4) ArrayList is better for storing and LinkedList is better for manipulating

accessing data. data.

5) The memory location for the elements of The location for the elements of a

an ArrayList is contiguous. linked list is not contagious.

6) Generally, when an ArrayList is initialized, a There is no case of default capacity

default capacity of 10 is assigned to the in a LinkedList. In LinkedList, an

ArrayList. empty list is created when a

LinkedList is initialized.

7) To be precise, an ArrayList is a resizable LinkedList implements the doubly

array. linked list of the list interface.

Points to Remember
The following are some important points to remember regarding an ArrayList and
LinkedList.

○ When the rate of addition or removal rate is more than the read scenarios, then go for
the LinkedList. On the other hand, when the frequency of the read scenarios is more
than the addition or removal rate, then ArrayList takes precedence over LinkedList.

○ Since the elements of an ArrayList are stored more compact as compared to a


LinkedList; therefore, the ArrayList is more cache-friendly as compared to the
LinkedList. Thus, chances for the cache miss are less in an ArrayList as compared to
a LinkedList. Generally, it is considered that a LinkedList is poor in cache-locality.

○ Memory overhead in the LinkedList is more as compared to the ArrayList. It is


because, in a LinkedList, we have two extra links (next and previous) as it is required
to store the address of the previous and the next nodes, and these links consume
extra space. Such links are not present in an ArrayList.

Java ListIterator Interface


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

ListIterator Interface declaration


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

Methods of Java ListIterator Interface:

Method Description

void add(E e) This method inserts the specified element into the list.

boolean This method returns true if the list iterator has more elements while

hasNext() traversing the list in the forward direction.

E next() This method returns the next element in the list and advances the

cursor position.
int This method returns the index of the element that would be returned

nextIndex() by a subsequent call to next()

boolean This method returns true if this list iterator has more elements while

hasPrevious( traversing the list in the reverse direction.

E previous() This method returns the previous element in the list and moves the

cursor position backward.

E This method returns the index of the element that would be returned

previousInde by a subsequent call to previous().

x()

void This method removes the last element from the list that was returned

remove() by next() or previous() methods

void set(E e) This method replaces the last element returned by next() or previous()

methods with the specified element.

Example of ListIterator Interface


import java.util.*;

public class ListIteratorExample1{


public static void main(String args[]){

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

al.add("Amit");

al.add("Vijay");

al.add("Kumar");

al.add(1,"Sachin");

ListIterator<String> itr=al.listIterator();

System.out.println("Traversing elements in forward direction");

while(itr.hasNext()){

System.out.println("index:"+itr.nextIndex()+" value:"+itr.next());

System.out.println("Traversing elements in backward direction");

while(itr.hasPrevious()){

System.out.println("index:"+itr.previousIndex()+" value:"+itr.previous());

}
Java HashSet

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

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Methods of Java HashSet class

Various methods of Java HashSet class are as follows:

SN Modi Method Description


fier
&
Type

1) boolea add(E e) It is used to add the specified element to this set if it is

n not already present.

2) void clear() It is used to remove all of the elements from the set.
3) object clone() It is used to return a shallow copy of this HashSet

instance: the elements themselves are not cloned.

4) boolea contains( It is used to return true if this set contains the specified

n Object o) element.

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

6) Iterato iterator() It is used to return an iterator over the elements in this

r<E> set.

7) boolea remove(O It is used to remove the specified element from this set if

n bject o) it is present.

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

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered
collection.

import java.util.*;
class HashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

HashSet<String> set=new HashSet();

set.add("One");

set.add("Two");

set.add("Three");

set.add("Four");

set.add("Five");

Iterator<String> i=set.iterator();

while(i.hasNext())

System.out.println(i.next());

}
Java LinkedHashSet Class

Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set
interface. It inherits the HashSet class and implements the Set interface.

The important points about the Java LinkedHashSet class are:

○ Java LinkedHashSet class contains unique elements only like HashSet.

○ Java LinkedHashSet class provides all optional set operations and permits null
elements.

○ Java LinkedHashSet class is non-synchronized.

○ Java LinkedHashSet class maintains insertion order.


Note: Keeping the insertion order in the LinkedHashset has some additional costs, both in terms
of extra memory and extra CPU cycles. Therefore, if it is not required to maintain the insertion
order, go for the lighter-weight HashMap or the HashSet instead.

Hierarchy of LinkedHashSet class

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

LinkedHashSet Class Declaration

Let's see the declaration for java.util.LinkedHashSet class.

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


Serializable

Constructors of Java LinkedHashSet Class

Constructor Description

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

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

collection c.
LinkedHashSet(int It is used to initialize the capacity of the linked hash set to the

capacity) given integer value capacity.

LinkedHashSet(int It is used to initialize both the capacity and the fill ratio (also

capacity, float fillRatio) called load capacity) of the hash set from its argument.

Java LinkedHashSet Example

Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the
elements iterate in insertion order.

FileName: LinkedHashSet1.java

import java.util.*;

class LinkedHashSet1{

public static void main(String args[]){

//Creating HashSet and adding elements

LinkedHashSet<String> set=new LinkedHashSet();

set.add("One");

set.add("Two");

set.add("Three");

set.add("Four");
set.add("Five");

Iterator<String> i=set.iterator();

while(i.hasNext())

System.out.println(i.next());

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.

○ The TreeSet can only allow those generic types that are comparable. For example The
Comparable interface is being implemented by the StringBuffer class.

Synchronization of The TreeSet Class

As already mentioned above, the TreeSet class is not synchronized. It means if more than
one thread concurrently accesses a tree set, and one of the accessing threads modify it,
then the synchronization must be done manually. It is usually done by doing some object
synchronization that encapsulates the set. However, in the case where no such object is
found, then the set must be wrapped with the help of the Collections.synchronizedSet()
method. It is advised to use the method during creation time in order to avoid the
unsynchronized access of the set. The following code snippet shows the same.

1. TreeSet treeSet = new 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 java.util.TreeSet class.

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


Cloneable, Serializable

Constructors of Java TreeSet Class

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<? It is used to build a new tree set that contains the elements of

extends E> c) the collection c.

TreeSet(Comparator<? It is used to construct an empty tree set that will be sorted

super E> comparator) according to given comparator.

TreeSet(SortedSet<E> It is used to build a TreeSet that contains the elements of the

s) given SortedSet.
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 It is used to add all of the elements in the

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

Comparator<? super E> comparator() It returns a comparator that arranges elements

in order.

Iterator descendingIterator() It is used to 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

boolean inclusive) than or equal to(if, inclusive is true) 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.

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

order.

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.

Spliterator spliterator() It is used to create a late-binding and fail-fast

spliterator over the elements.

NavigableSet subSet(E fromElement, It returns a set of elements that lie between the

boolean fromInclusive, E toElement, given range.

boolean toInclusive)

SortedSet subSet(E fromElement, E It returns a set of elements that lie between the

toElement)) given range which includes fromElement and

excludes toElement.

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

boolean inclusive) or equal to (if, inclusive is true) the specified

element.

boolean contains(Object o) It returns true if this set contains the specified

element.

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

boolean remove(Object o) It is used to remove the specified element from

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

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.

Java TreeSet Examples

Java TreeSet Example 1:

Let's see a simple example of Java TreeSet.

FileName: TreeSet1.java

import java.util.*;

class TreeSet1{

public static void main(String args[]){

//Creating and adding elements

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

al.add("Ravi");

al.add("Vijay");

al.add("Ravi");

al.add("Ajay");

//Traversing elements
Iterator<String> itr=al.iterator();

while(itr.hasNext()){

System.out.println(itr.next());

—-----

import java.util.*;

class TreeSet3{

public static void main(String args[]){

TreeSet<Integer> set=new TreeSet<Integer>();

set.add(24);

set.add(66);

set.add(12);

set.add(15);

System.out.println("Lowest Value: "+set.pollFirst());

System.out.println("Highest Value: "+set.pollLast());

You might also like