Why does set.size()
show different values for String and Java Object when they are for Duplicate elements?
If I insert duplicate values in String and run set.size() it only counts the unique elements, but in Object, when I insert duplicate values it counts the total, including the duplicate itself. Why is this?
FIRST PROGRAM
==============
/** Insert Duplicate in String **/
public class SetDemo {
public static void main(String[] args) {
Set<String> set = new HashSet<>();
// Insert duplicate values
set.add("Rai");
set.add("Rai");
set.add("Tama");
// show set size
System.out.println(set.size());
}
}
Output: 2
=======================================================================
SECOND PROGRAM
====================
/* Insert Duplicate in Object */
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id,String name,String author,String publisher,int quantity)
{
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}
public class HashSetExample {
public static void main(String[] args) {
HashSet<Book> set=new HashSet<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications &
Networking","Forouzan","Mc Graw Hill",4);
// Insert duplicate values
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
Book b4=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to HashSet
set.add(b1);
set.add(b2);
set.add(b3);
set.add(b4);
//Traversing HashSet
for(Book b:set){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+"
"+b.quantity);
}
// show set size
System.out.println(set.size());
}
}
Output: 4
If I insert duplicate values in String and run set.size()
it only counts the unique elements, but in Object, when I insert duplicate values it counts the total, including the duplicate itself. Why is this? In the First program duplicate values are not allowed but in the Second program set.size()
should be 3 yet it shows 4