0% found this document useful (0 votes)
35 views8 pages

Java Set Operations Example Code

Noteeeee

Uploaded by

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

Java Set Operations Example Code

Noteeeee

Uploaded by

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

Dt : 10/11/2022

Ex-program : [Link]

package maccess;
import [Link].*;
public class DemoSet1 {
@SuppressWarnings({ "rawtypes", "unchecked", "removal" })
public static void main(String[] args) {
//Set object created to hold Unlimited any type of
Objects
HashSet ob1 = new HashSet();

ii
[Link](new Integer(123));//Adding Integer Object to Set

ath
[Link](new String("NIT"));//Adding String Object to Set
[Link](new StringBuffer("Java"));//Adding Buffer object
Set
[Link]("****display from Set<E>*****");
[Link]([Link]());

aip
//Set object created to hold Unlimited Integer Objects
HashSet<Integer> ob2 = new HashSet<Integer>();
[Link](new Integer(11));
hM
[Link](new Integer(10));
[Link](new Integer(16));
[Link]([Link]());

//Set object created to hold Unlimited String Objects


HashSet<String> ob3 = new HashSet<String>();
tes

[Link](new String("Task"));
[Link](new String("Thread"));
[Link](new String("Test"));
[Link]([Link]());
a
nk

}
}
Ve

o/p:

****display from Set<E>*****

[NIT, 123, Java]

[16, 10, 11]

[Task, Test, Thread]


====================================================================

Ex-Program : [Link]

package maccess;
import [Link].*;
public class DemoSet2 {
@SuppressWarnings("removal")
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
String name=null;
Set<Integer> ob = null;

ii
try(s;){

ath
try {
while(true) {
[Link]("****Choice*****");

aip
[Link]("[Link]\[Link]\[Link]\[Link]
t");
[Link]("Enter the Choice:");
switch([Link]()) {
hM
case 1:
ob = new HashSet<Integer>();
name="HashSet";
break;
case 2:
ob = new LinkedHashSet<Integer>();
tes

name="LinkedHashSet";
break;
case 3:
ob = new TreeSet<Integer>();
a

name="TreeSet";
nk

break;
case 4:
[Link]("Operations stopped
of Set");
Ve

[Link](0);
break;
default:
[Link]("Invalid
Choice...");
}//end of switch
[Link]("****Operations on
"+name+"****");
xyz:
while(true) {
[Link]("****Choice****");

[Link]("[Link]\[Link]\[Link]");
[Link]("Enter the
Choice:");
switch([Link]()) {
case 1:
[Link]("Enter the
ele:");
[Link](new Integer([Link]()));
[Link]([Link]());

ii
break;
case 2:

ath
if([Link]()) {
[Link]("Set is
empty...");
}else {
[Link]("Enter the

aip
ele to be removed:");
if([Link](new
Integer([Link]()))) {
[Link]("Ele
hM
removed Successfully..");

[Link]([Link]());
}else {
[Link]("Element
tes

not founded...");
}
}
break;
case 3:
a

[Link]("Operations
nk

Stopped on "+name);
break xyz;
default:
[Link]("Invalid
Ve

Choice...");
}//end of switch
}//end of while

}//end of loop
}catch(Exception e) {[Link]();}
}//end of try
}
}
=================================================================

*imp

Set<E> holding Usser defined class Objects:

[Link]

package test;
public class BookDetails extends Object{

ii
//Instance Variables

ath
public String code,name,author;
public float price;
public int qty;

//Constructor to initialize Instance variables

aip
public BookDetails(String code,String name,String
author,float price,int qty){
[Link]=code;
[Link]=name;
hM
[Link]=author;
[Link]=price;
[Link]=qty;
}
@Override
public String toString()
tes

{
return code+"\t"+name+"\t"+author+"\t"+price+"\t"+qty;
}
}
a
nk

[Link](MainClass)

package maccess;
Ve

import [Link].*;

import test.*;

public class DemoSet3 {

@SuppressWarnings("removal")

public static void main(String[] args) {


Scanner s = new Scanner([Link]);

String name=null;

Set<BookDetails> ob = null;

try(s;){

try {

while(true) {

ii
[Link]("****Choice*****");

ath
[Link]("[Link]\[Link]\[Link]\[Link]");

[Link]("Enter the Choice:");

aip
switch([Link]([Link]())) {

case 1:
hM
ob = new HashSet<BookDetails>();

name="HashSet";

break;
tes

case 2:

ob = new LinkedHashSet<BookDetails>();
a

name="LinkedHashSet";
nk

break;

case 3:
Ve

ob = new TreeSet<BookDetails>();

name="TreeSet";

break;

case 4:

[Link]("Operations stopped of Set");


[Link](0);

break;

default:

[Link]("Invalid Choice...");

}//end of switch

[Link]("****Operations on "+name+"****");

ii
xyz:

ath
while(true) {

[Link]("****Choice****");

aip
[Link]("[Link]\[Link]\[Link]\[Link]");

[Link]("Enter the Choice:");


hM
switch([Link]([Link]())) {

case 1:

[Link]("Enter the code:");


tes

String bC=[Link]();

[Link]("Enter the name:");


a

String bN=[Link]();
nk

[Link]("Enter the author:");

String bA=[Link]();
Ve

[Link]("Enter the price:");

float bP = [Link]([Link]());

[Link]("Enter the qty:");

int bQ = [Link]([Link]());

[Link](new BookDetails(bC,bN,bA,bP,bQ));
[Link]("BookDetails added Successfully..");

break;

case 2:

if([Link]()) {

[Link]("Set is empty...");

}else {

ii
[Link]("Enter the ele(code) to be removed:");

ath
String code2 = [Link]();

boolean p=false;

aip
Iterator<BookDetails> it = [Link]();

while([Link]())
hM
{

BookDetails bd = (BookDetails)[Link]();

if([Link](code2)) {
tes

p=true;

[Link](bd);
a

[Link]("Ele removed Successfully..");


nk

break;

}
Ve

}//end of loop

if(!p)

[Link]("Element Not found...");

}
}

break;

case 3:

[Link]("****BookDetails****");

[Link]((k)->

ii
[Link]([Link]());

ath
});

break;

aip
case 4:

[Link]("Operations Stopped on "+name);


hM
break xyz;

default:

[Link]("Invalid Choice...");
tes

}//end of switch

}//end of while
a
nk

}//end of loop

}catch(Exception e) {[Link]();}
Ve

}//end of try

==============================================================

Common questions

Powered by AI

Using TreeSet in DemoSet3.java with custom objects such as BookDetails poses challenges primarily due to TreeSet's reliance on natural ordering for element arrangement. By default, Java does not know how to order custom objects without implementing the Comparable interface or providing a Comparator. Without these, adding BookDetails objects to a TreeSet will result in a ClassCastException. To mitigate this, either the BookDetails class should implement the Comparable interface where the `compareTo` method defines logical ordering, or a separate Comparator should be supplied during TreeSet construction. This ensures elements are correctly ordered, aligning with TreeSet's requirements.

The polymorphic use of Set objects in DemoSet2.java is a key aspect of its robust design. By utilizing a common Set interface to define variables (e.g., `Set<Integer> ob`), the program takes advantage of polymorphism to allow for substituting different concrete implementations of the Set, such as HashSet, LinkedHashSet, or TreeSet, based on user choice. This design encapsulates the specifics of the Set implementation while exposing a consistent interface for interacting with collections. This flexibility reduces code duplication, allows for easier extension and maintenance, and enhances robustness, as changes in implementation do not necessitate changes in the code that uses the collection.

In the DemoSet1.java program, three different HashSet objects manage different types of elements. The first HashSet (ob1) allows for holding any type of objects, demonstrated by adding an Integer, a String, and a StringBuffer. The second HashSet (ob2) is explicitly defined to manage only Integer objects due to the use of a generic type parameter (HashSet<Integer>). The third HashSet (ob3) is defined to manage only String objects, also accomplished by using a generic type parameter (HashSet<String>). These differences illustrate the use of generics in Java to ensure type safety and specificity in collections.

DemoSet1.java demonstrates core principles of data structure manipulation through Java collections by showcasing the use of HashSet to manage different data types. It highlights the versatility and flexibility of Java's collection framework through the instantiation of HashSet objects with different type parameters (using generics) to hold heterogeneous or homogeneous types (e.g., all Integers or all Strings). The program further showcases fundamental operations on sets, such as adding elements and displaying the set's content, emphasizing the automatic handling of duplicate checks and order maintenance with various HashSet instances. This demonstration underpins key data structure principles: abstraction, encapsulation, and type safety.

The menu-driven structure in DemoSet2.java enhances user control over collection operations by presenting clear choices and step-by-step instructions, reducing the cognitive load on users. By leveraging a text-based menu for choosing Set types and subsequent operations such as adding or removing elements, it organizes interaction flow in intuitive, manageable chunks. This design ensures efficient navigation through operations, helping users focus on one task at a time without being overwhelmed by complexities of the underlying data structures. It also aids in preventing errors by providing a structured guide through legal operations, thereby enhancing operational efficiency and user satisfaction.

DemoSet3.java exemplifies user interaction design by incorporating a menu-driven interface that facilitates the management of a book collection via prompts for adding, removing, displaying, and structured exiting. This approach underscores ease of use, aimed at guiding users through interaction steps clearly. Design considerations likely included minimizing user errors through validation (e.g., handling empty sets on removal attempts), providing informative feedback (e.g., success/failure messages), and ensuring flexible command execution (choice between HashSet, LinkedHashSet, TreeSet). The design prioritizes usability and user-friendly software interaction, allowing users to manage collections intuitively while maintaining controlled operational flow.

DemoSet3.java demonstrates encapsulation and abstraction by using a user-defined class, BookDetails, to encapsulate data related to books (code, name, author, price, quantity). This class abstracts the details of book data management and provides a coherent interface through the `toString()` method for easy representation. The class's design confines how book data is stored and manipulated, exposing only necessary functionalities. By incorporating BookDetails objects within a Set collection, additional abstraction is achieved, where the underlying data structure (Set type) that manages the BookDetails objects further encapsulates operational details such as ordering and storage mechanics, presenting a streamlined interface to end users.

DemoSet3.java manages potential exceptions during interactive sessions primarily through try-catch blocks that secure user input and collection manipulation processes. This basic exception handling ensures that unexpected errors or invalid operations (e.g., input mismatches, empty collections manipulation) do not crash the program, providing controlled error management and debugging insights through stack traces. However, improvements could include more specific exception handling, such as catching InputMismatchException for invalid user input and number format exceptions separately. Integrating user-friendly error messages to inform users of corrective actions, rather than only re-throwing stack traces, could enhance robustness and user experience.

In DemoSet3.java, an iterator is used to traverse the Set of BookDetails objects. It is specifically employed when removing a specific book entry based on its code. The iterator allows for safe removal of elements during iteration because it can handle the underlying modifications to the collection, preventing ConcurrentModificationException. However, directly modifying a collection during iteration without using an iterator can risk throwing this exception, as it disrupts the integrity of the iteration process. The iterator ensures consistency and avoids unexpected behavior when elements are removed.

DemoSet2.java employs user input to allow for the dynamic selection of a Set type via a switch statement. The program prompts users to choose between HashSet, LinkedHashSet, and TreeSet. This flexibility enables the software to adapt to various data handling needs based on the selected Set implementation. Each type of Set offers distinct properties: HashSet is unordered, LinkedHashSet maintains insertion order, and TreeSet orders elements naturally. This choice facilitates tailored performance and behavior characteristics, demonstrating a flexible software system that can be configured at runtime to optimize for specific needs based on user input.

You might also like