Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Java Utillity

The document provides an overview of Java Collections and Utility Classes, focusing on generics, the Collections class, and the ArrayList and Vector implementations. It explains the creation and manipulation of generic classes and methods, along with the features, advantages, and disadvantages of ArrayLists and Vectors. Additionally, it covers operations such as adding, removing, and iterating elements in ArrayLists, as well as constructors and synchronization aspects of Vectors.

Uploaded by

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

Java Utillity

The document provides an overview of Java Collections and Utility Classes, focusing on generics, the Collections class, and the ArrayList and Vector implementations. It explains the creation and manipulation of generic classes and methods, along with the features, advantages, and disadvantages of ArrayLists and Vectors. Additionally, it covers operations such as adding, removing, and iterating elements in ArrayLists, as well as constructors and synchronization aspects of Vectors.

Uploaded by

Anvi Suri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Unit-2

Java Collections and Utility Classes

Introductions to generics: generic types and methods Collection Basics- A Collection


Hierarchy, Using ArrayList and Vector, LinkedList Making use of Iterator to access
collection elements. UsingSet CollectionsHashSet, LinkedHashSet and TreeSet Using
Dictionary. By Gargi Mukherjee
Generics
Generic classes
• Generic Classes: A generic class is implemented exactly like a non-generic
class. The only difference is that it contains a type parameter section. There
can be more than one type of parameter, separated by a comma. The classes,
which accept one or more parameters, are known as parameterized classes or
parameterized types.
• To create objects of a generic class, we use the following syntax.

• // To create an instance of generic class


• BaseType <Type> obj = new BaseType <Type>()
• // Java program to show working of user defined Generic classes
• class Test<T> {
• // An object of type T is declared
• T obj;
• Test(T obj) { this.obj = obj; } // constructor
• public T getObject() { return this.obj; }
• }
• class Main {
• public static void main(String[] args)
• { // instance of Integer type
• Test<Integer> iObj = new Test<Integer>(15);
• System.out.println(iObj.getObject());
• // instance of String type
• Test<String> sObj
• = new Test<String>("GeeksForGeeks");
• System.out.println(sObj.getObject()); }}
Multiple Parameters
• // Java program to show multiple type parameters in Java Generics
• class Test<T, U>
• { T obj1; // An object of type T
• U obj2; // An object of type U
• Test(T obj1, U obj2)
• { this.obj1 = obj1;
• this.obj2 = obj2; }
• // To print objects of T and U
• public void print()
• { System.out.println(obj1);
• System.out.println(obj2); }}
• class Main
• { public static void main (String[] args)
• { Test <String, Integer> obj =new Test<String, Integer>("GfG", 15);
• obj.print();}}
• // Java program to show working of user defined Generic functions
• class Test {
• // A Generic method example
• static <T> void genericDisplay(T element)
• {
• System.out.println(element.getClass().getName() + " = " + element);
• }
• public static void main(String[] args)
• {
• // Calling generic method with Integer argument
• genericDisplay(11);

• // Calling generic method with String argument


• genericDisplay(“hellos");
• // Calling generic method with double argument
• genericDisplay(1.0); }}
Type Parameters in Java Generics

• The type parameters naming conventions are important to learn generics


thoroughly. The common type parameters are as follows:

• T – Type
• E – Element
• K – Key
• N – Number
• V – Value
Collections Class in Java
• Collections class in Java is one of the utility classes in Java Collections
Framework. The java.util package contains the Collections class in Java. Java
Collections class is used with the static methods that operate on the
collections or return the collection. All the methods of this class throw
the NullPointerException if the collection or object passed to the methods
is null.
• Collection Class declaration
• The syntax of the Collection class declaration is mentioned below:
• public class Collections extends Object
Note: Object is the parent class of all the
classes.
• Java Collection Class
• Collection Framework contains both classes and interfaces.
• 1. ArrayList
• ArrayList is a class implemented using a list interface, in that provides the
functionality of a dynamic array where the size of the array is not fixed.
• Syntax:
• ArrayList<_type_> var_name = new ArrayList<_type_>();
• 2. Vector
• Vector is a Part of the collection class that implements a dynamic array that
can grow or shrink its size as required.

• Syntax:
• public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess,
• Cloneable, Serializable
ArrayList in Java
• Java ArrayList is a part of the Java collection framework and it is a class of
java.util package. It provides us with dynamic arrays in Java.
• It may be slower than standard arrays but can be helpful in programs where lots of
manipulation in the array is needed.
• The main advantage of Java ArrayList is, if we declare an array then we need to
mention the size, but in ArrayList, it is not needed to mention the size of ArrayList.
What is ArrayList in Java?
• ArrayList is a Java class implemented using the List interface. Java ArrayList, as the
name suggests, provides the functionality of a dynamic array where the size is not
fixed as an array. Also, as a part of the Collection framework, it has many features
not available with arrays.

illustration
how to create and use an ArrayList with a mention of its size.
• import java.io.*;
• import java.util.*;
• class ArrayListExample {
• public static void main(String[] args)
• { // Size of the ArrayList
• int n = 5;
• // Declaring the ArrayList with initial size n
• ArrayList<Integer> arr1 = new ArrayList<Integer>(n);
• // Declaring the ArrayList
• ArrayList<Integer> arr2 = new ArrayList<Integer>();
• // Printing the ArrayList
• System.out.println("Array 1:" + arr1);System.out.println("Array 2:" + arr2);
• // Appending new elements at the end of the list
• for (int i = 1; i <= n; i++) { arr1.add(i); arr2.add(i); }
• // Printing the ArrayList
• System.out.println("Array 1:" + arr1);
• System.out.println("Array 2:" + arr2); }}
Output
• Array 1:[]
• Array 2:[]
• Array 1:[1, 2, 3, 4, 5]
• Array 2:[1, 2, 3, 4, 5]
Explanation of the above Program:
• ArrayList is a dynamic array and we do not have to specify the size while creating it, the size
of the array automatically increases when we dynamically add and remove items. Though the
actual library implementation may be more complex, the following is a very basic idea
explaining the working of the array when the array becomes full and if we try to add an
item:
• Creates a bigger-sized memory on heap memory (for example memory of double size).
• Copies the current memory elements to the new memory.
• The new item is added now as there is bigger memory available now.
• Delete the old memory.
Important Features of ArrayList in Java
• ArrayList inherits AbstractList class and implements the List interface.
• ArrayList is initialized by size. However, the size is increased automatically if
the collection grows or shrinks if the objects are removed from the
collection.
• Java ArrayList allows us to randomly access the list.
• ArrayList can not be used for primitive types like int, char, etc. We need a
wrapper class for such cases.
• ArrayList in Java can be seen as a vector in C++.
• ArrayList is not Synchronized. Its equivalent synchronized class in Java is
Vector.
Hierarchy Java ArrayList
Constructors in ArrayList
• In order to create an ArrayList, we need to create an object of the ArrayList
class. The ArrayList class consists of various constructors which allow the
possible creation of the array list. The following are the constructors
available in this class:
• 1. ArrayList()
• This constructor is used to build an empty array list. If we wish to create an
empty ArrayList with the name arr, then, it can be created as:
• ArrayList arr = new ArrayList();
• 2. ArrayList(Collection c)
• This constructor is used to build an array list initialized with the elements
from the collection c. Suppose, we wish to create an ArrayList arr which
contains the elements present in the collection c, then, it can be created as:
• ArrayList arr = new ArrayList(c);
• 3. ArrayList(int capacity)
• This constructor is used to build an array list with the initial capacity being
specified. Suppose we wish to create an ArrayList with the initial size being
N, then, it can be created as:

• ArrayList arr = new ArrayList(N);


Operations performed in ArrayList
• 1. Adding Elements
• In order to add an element to an ArrayList, we can use the add() method.
This method is overloaded to perform multiple operations based on different
parameters. They are as follows:
• add(Object): This method is used to add an element at the end of the
ArrayList.
• add(int index, Object): This method is used to add an element at a specific
index in the ArrayList.
// Java Program to Add elements to An ArrayList
// Importing all utility classes
import java.util.*;
class Arr {
// Main driver method
public static void main(String args[])
{
// Creating an Array of string type
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// Custom inputs
al.add("Arr");
al.add("Arr");
// Here we are mentioning the index
// at which it is to be added
al.add(1, "For");
// Printing all the elements in an ArrayList
System.out.println(al); }}
2. Changing Elements

• After adding the elements, if we wish to change the element, it can be done
using the set() method. Since an ArrayList is indexed, the element which we
wish to change is referenced by the index of the element. Therefore, this
method takes an index and the updated element which needs to be inserted
at that index.
• // Java Program to Change elements in ArrayList
• // Importing all utility classes
• import java.util.*;
• // main class
• class chel {
• // Main driver method
• public static void main(String args[])
• { // Creating an Arraylist object of string type
• ArrayList<String> al = new ArrayList<>();
• // Adding elements to Arraylist
• // Custom input elements
• al.add("Greet"); al.add("Greet");
• // Adding specifying the index to be added
• al.add(1, "hello");
• // Printing the Arraylist elements
• System.out.println("Initial ArrayList " + al);
• // Setting element at 1st index
• al.set(1, "For");
• // Printing the updated Arraylist
• System.out.println("Updated ArrayList " + al); }}
3. Removing Elements
• In order to remove an element from an ArrayList, we can use the remove()
method. This method is overloaded to perform multiple operations based on
different parameters. They are as follows:
• remove(Object): This method is used to simply remove an object from the
ArrayList. If there are multiple such objects, then the first occurrence of the
object is removed.
• remove(int index): Since an ArrayList is indexed, this method takes an
integer value which simply removes the element present at that specific index
in the ArrayList. After removing the element, all the elements are moved to
the left to fill the space and the indices of the objects are updated.
• // Java program to Remove Elements in ArrayList
• // Importing all utility classes
• import java.util.*;
• class GRem{
• public static void main(String args[])
• { rrayList<String> al = new ArrayList<>();
• // Adding elements to ArrayList
• // Custom addition
• al.add("Great"); al.add("Great");
• // Adding element at specific index
• al.add(1, "For");
• // Printing all elements of ArrayList
• System.out.println("Initial ArrayList " + al);
• // Removing element from above ArrayList
• al.remove(1);
• // Printing the updated Arraylist elements
• System.out.println("After the Index Removal " + al);
• // Removing this word element in ArrayList
• al.remove("Great");
• // Now printing updated ArrayList
• System.out.println("After the Object Removal "+ al); }}
4. Iterating the ArrayList
• There are multiple ways to iterate through the ArrayList. The most famous ways are by using the basic for loop in combination
with a get() method to get the element at a specific index and the advanced for a loop.
• import java.util.*;
• class GFG {
• // Main driver method
• public static void main(String args[])
• { ArrayList<String> al = new ArrayList<>();
• // Adding elements to ArrayList
• // using standard add() method
• al.add("Geeks");
• al.add("Geeks");
• al.add(1, "For");
• // Using the Get method and the
• // for loop
• for (int i = 0; i < al.size(); i++) {
• System.out.print(al.get(i) + " "); }
• System.out.println();
• for (String str : al)
• System.out.print(str + " "); }}
• ArrayList in Java is a class in the Java Collection framework that implements the List
interface. Here are the advantages and disadvantages of using ArrayList in Java.

• Advantages of Java ArrayList


• Dynamic size: ArrayList can dynamically grow and shrink in size, making it easy to
add or remove elements as needed.
• Easy to use: ArrayList is simple to use, making it a popular choice for many Java
developers.
• Fast access: ArrayList provides fast access to elements, as it is implemented as an
array under the hood.
• Ordered collection: ArrayList preserves the order of elements, allowing you to
access elements in the order they were added.
• Supports null values: ArrayList can store null values, making it useful in cases where
the absence of a value needs to be represented.
Disadvantages of Java ArrayList

• Slower than arrays: ArrayList is slower than arrays for certain operations, such as
inserting elements in the middle of the list.
• Increased memory usage: ArrayList requires more memory than arrays, as it needs
to maintain its dynamic size and handle resizing.
• Not thread-safe: ArrayList is not thread-safe, meaning that multiple threads may
access and modify the list concurrently, leading to potential race conditions and data
corruption.
• Performance degradation: ArrayList’s performance may degrade as the number of
elements in the list increases, especially for operations such as searching for
elements or inserting elements in the middle of the list.
Points to be noted
• ArrayList is the part of Collection framework. It inherits the AbstractList
class and implements the List interface.
• ArrayList is the implementation of a dynamic array.
• ArrayList can be initialized used using different constructor types like
without parameters, passing collection as a parameter, and passing integer as
a parameter.
• Operations can be performed in ArrayList as follows Adding, removing,
iterating, and sorting.
vector
• Vector implements a dynamic array which means it can grow or shrink as
required. Like an array, it contains components that can be accessed using an
integer index.
• They are very similar to ArrayList, but Vector is synchronized and has some
legacy methods that the collection framework does not contain.
• It also maintains an insertion order like an ArrayList. Still, it is rarely used in
a non-thread environment as it is synchronized, and due to this, it gives a
poor performance in adding, searching, deleting, and updating its elements.
syntax
• public class Vector<E> extends AbstractList<E> implements List<E>,
RandomAccess, Cloneable, Serializable
• It extends AbstractList and implements List interfaces.
• It implements Serializable, Cloneable, Iterable<E>, Collection<E>,
List<E>, RandomAccess interfaces.
• The directly known subclass is Stack.
Constructors
1. Vector(): Creates a default vector of the initial capacity is 10.
• Vector<E> v = new Vector<E>();
2. Vector(int size): Creates a vector whose initial capacity is specified by size.
• Vector<E> v = new Vector<E>(int size);
3. Vector(int size, int incr): Creates a vector whose initial capacity is specified by size
and increment is specified by incr. It specifies the number of elements to allocate each
time a vector is resized upward.

• Vector<E> v = new Vector<E>(int size, int incr);


4. Vector(Collection c): Creates a vector that contains the elements of collection c.
• Vector<E> v = new Vector<E>(Collection c);
METHOD DESCRIPTION

Appends the specified element to the end of this


add(E e)
Vector.

Inserts the specified element at the specified


add(int index, E element)
position in this Vector.

clear() Removes all of the elements from this Vector.

Removes the element at the specified position in


remove(int index)
this Vector.

Replaces the element at the specified position in


set(int index, E element)
this Vector with the specified element.
advantages
• Synchronization: As mentioned before, Vector is synchronized, making it safe to use in a
multi-threaded environment.
• Dynamic Size: The size of a Vector can grow or shrink dynamically as elements are added or
removed, so you don’t have to worry about setting an initial size that will accommodate all
elements.
• Legacy support: Vector has been part of Java since its inception and is still supported, so it’s
a good option if you need to work with older Java code that uses Vector.
• Disadvantages of using Vector in Java:
• Performance: The synchronization in Vector can lead to slower performance compared to
other collection classes, such as ArrayList.
• Legacy Code: While Vector is still supported, newer Java code is often written using the
more modern collection classes, so it may be harder to find examples and support for
Vector.
• Unnecessary overhead: If you don’t need the synchronization features of ‘vector
LinkedList
• Linked List is a part of the Collection framework present in java.util package. This class is
an implementation of the LinkedList data structure which is a linear data structure where
the elements are not stored in contiguous locations and every element is a separate object
with a data part and address part.
• The elements are linked using pointers and addresses. Each element is known as a node.
Since a LinkedList acts as a dynamic array and we do not have to specify the size while
creating it, the size of the list automatically increases when we dynamically add and remove
items.
• And also, the elements are not stored in a continuous fashion. Therefore, there is no need
to increase the size. Internally, the LinkedList is implemented using the doubly linked list
data structure.

• The main difference between a normal linked list and a doubly LinkedList is that a doubly
linked list contains an extra pointer, typically called the previous pointer, together with the
next pointer and data which are there in the singly linked list.
Constructors in the LinkedList:
Method Description

This method Inserts the specified element at the specified


add(int index, E element)
position in this list.

This method Appends the specified element to the end of this


add(E e)
list.

This method pushes an element onto the stack represented


push(E e)
by this list.

This method retrieves and removes the head (first element)


remove()
of this list.

This method removes the element at the specified position in


remove(int index)
this list.

This method Pops an element from the stack represented by


pop()
this list.

This method replaces the element at the specified position in


set(int index, E element)
this list with the specified element.

size() This method returns the number of elements in this list.


Advantages of using LinkedList in Java:

• Dynamic size: As with Vector, the size of a LinkedList can grow or shrink
dynamically, so you don’t have to worry about setting an initial size.
• Efficient Insertions and Deletions: LinkedList is an efficient data structure for
inserting or deleting elements in the middle of the list because you only need to
change the links between elements, rather than shifting all elements after the
insertion or deletion point.
• Flexible Iteration: With a linked list, you can efficiently iterate through the list in
either direction, since each element has a reference to both its predecessor and
successor elements.
Disadvantages of using LinkedList in Java:

• Performance: LinkedList has a slower performance than ArrayList when it


comes to accessing individual elements. This is because you need to traverse
the list to reach the desired element, whereas with ArrayList, you can simply
access the desired element using an index.
• Memory overhead: LinkedList requires more memory than ArrayList because
each element requires additional memory for the links to its predecessor and
successor elements.
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.
• public class HashSet<E> extends AbstractSet<E> implements Set<E>,
Cloneable, Serializable

SN Constructor Description
1) HashSet() It is used to construct a default HashSet.

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

A list can contain duplicate elements whereas Set contains unique elements only.
The HashSet class extends AbstractSet class which implements Set interface. The Set interface
inherits Collection and Iterable interfaces in hierarchical order. import java.util.*;
A HashSet is a collection of items where every item is unique, and it is found in the java.util
package:
• 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());
• }
• }
• }
Hashset for storing integers
• import java.util.HashSet;
• public class Main {
• public static void main(String[] args) {
• // Create a HashSet object called numbers
• HashSet<Integer> numbers = new HashSet<Integer>();
• // Add values to the set
• numbers.add(4);
• numbers.add(7);
• numbers.add(8);
• // Show which numbers between 1 and 10 are in the set
• for(int i = 1; i <= 10; i++) {
• if(numbers.contains(i)) {
• System.out.println(i + " was found in the set.");
• } else {
• System.out.println(i + " was not found in the set."); } } }}
Java Iterator
• An Iterator is an object that can be used to loop through collections, like
ArrayList and HashSet. It is called an "iterator" because "iterating" is the
technical term for looping.

• To use an Iterator, you must import it from the java.util package.


• The iterator() method can be used to get an Iterator for any collection
• import java.util.ArrayList;
• import java.util.Iterator;
• public class Main {
• public static void main(String[] args) {
• // Make a collection
• ArrayList<String> cars = new ArrayList<String>();
• cars.add("Volvo");
• cars.add("BMW");
• cars.add("Ford");
• cars.add("Mazda");
• // Get the iterator
• Iterator<String> it = cars.iterator();
• // Print the first item
• System.out.println(it.next()); }}
Removing items from collection-Iterators are designed to easily change the collections that they loop
through. The remove() method can remove items from a collection while looping

• import java.util.ArrayList;
• import java.util.Iterator;
• public class Main {
• public static void main(String[] args) {
• ArrayList<Integer> numbers = new ArrayList<Integer>();
• numbers.add(12);
• numbers.add(8);
• numbers.add(2);
• numbers.add(23);
• Iterator<Integer> it = numbers.iterator();
• while(it.hasNext()) {
• Integer i = it.next();
• if(i < 10) {
• it.remove(); } }
• System.out.println(numbers); }}
Java HashMap
• In the ArrayList chapter, you learned that Arrays store items as an ordered
collection, and you have to access them with an index number (int type). A
HashMap however, store items in "key/value" pairs, and you can access them
by an index of another type (e.g. a String).
• One object is used as a key (index) to another object (value). It can store
different types: String keys and Integer values, or the same type, like: String
keys and String values:
• Create a HashMap object called capitalCities that will store String keys and
String values:
• import java.util.HashMap; // import the HashMap class
• HashMap<String, String> capitalCities = new HashMap<String, String>();
Hashmap classes
• import java.util.HashMap;

• public class Main {


• public static void main(String[] args) {
• // Create a HashMap object called capitalCities
• HashMap<String, String> capitalCities = new HashMap<String, String>();

• // Add keys and values (Country, City)


• capitalCities.put("England", "London");
• capitalCities.put("Germany", "Berlin");
• capitalCities.put("Norway", "Oslo");
• capitalCities.put("USA", "Washington DC");
• System.out.println(capitalCities);
• }
• }
Access an Item
• To access a value in the HashMap, use the get() method and refer to its
key:
• capitalCities.get("England");
• Remove an Item
• To remove an item, use the remove() method and refer to the key:
capitalCities.remove("England");
HashMap Size
To find out how many items there are, use the size() method:
capitalCities.size();
• import java.util.HashMap;
• public class Main {
• public static void main(String[] args) {
• // Create a HashMap object called people
• HashMap<String, Integer> people = new HashMap<String, Integer>();
• // Add keys and values (Name, Age)
• people.put("John", 32);
• people.put("Steve", 30);
• people.put("Angie", 33);
• for (String i : people.keySet()) {
• System.out.println("key: " + i + " value: " + people.get(i)); } }}
LinkedHashSet in Java
• The LinkedHashSet is an ordered version of HashSet that maintains a
doubly-linked List across all elements. When the iteration order is needed to
be maintained this class is used. When iterating through a HashSet the order
is unpredictable, while a LinkedHashSet lets us iterate through the elements
in the order in which they were inserted. When cycling through
LinkedHashSet using an iterator, the elements will be returned in the order in
which they were inserted.
Syntax: Declaration

• public class LinkedHashSet<E> extends HashSet<E> implements Set<E>,


Cloneable, Serializable
• Contains unique elements only like HashSet. It extends the HashSet class and
implements the Set interface.
• Maintains insertion order.
Constructors of LinkedHashSet Class
• 1. LinkedHashSet(): This constructor is used to create a default HashSet

• LinkedHashSet<E> hs = new LinkedHashSet<E>();


• 2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements
of the collection C.

• LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);


• . LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the
integer mentioned in the parameter.

• LinkedHashSet<E> hs = new LinkedHashSet<E>(int size);


Performing Various Operations on the
LinkedHashSet Class
• Operation 1: Adding Elements
• In order to add an element to the LinkedHashSet, we can use the add()
method. This is different from HashSet because in HashSet, the insertion
order is not retained but is retained in the LinkedHashSet.
• Removing Elements
• The values can be removed from the LinkedHashSet using the remove()
method.
• Iterating through LinkedHashSet
• Iterate through the elements of LinkedHashSet using the iterator() method.
The most famous one is to use the enhanced for loop.
treeSet
• TreeSet is one of the most important implementations of the SortedSet
interface in Java that uses a Tree for storage. The ordering of the elements is
maintained by a set using their natural ordering whether or not an explicit
comparator is provided. This must be consistent with equals if it is to
correctly implement the Set interface.
• The navigable set extends the sorted set interface. Since a set doesn’t retain
the insertion order, the navigable set interface provides the implementation
to navigate through the Set. The class which implements the navigable set is
a TreeSet which is an implementation of a self-balancing tree. Therefore, this
interface provides us with a way to navigate through this tree.
• TreeSet serves as an excellent choice for storing large amounts of sorted
information which are supposed to be accessed quickly because of its faster
access and retrieval time. Here we will be performing various operations over
the TreeSet object to get familiar with the methods and concepts of TreeSet
in java. Let’s see how to perform a few frequently used operations on the
TreeSet. They are listed as follows:

• Adding elements
• Accessing elements
• Removing elements
• Iterating through elements

You might also like