If you try to add duplicate values to the Set, false will be returned.
When ever you add any object to the Set, boolean value will be returned. True will be returned, if it adds successfully and False will be returned, if it could not add the element. So if you are adding the duplicate elements, it will not add and false will be returned.
You can practice my code, which is attached at the bottom.
Comment the line, //(1) and you can see false values, try to add here some distinguish values(Say your name, "Rob Kiu"), you will see 'true' in the output.
---------
See the code.......
----
import java.util.*;
public class SetExample {
public void method(){
// Here i am creating the HastSet object, you can create other Set objects too.
HashSet setColl;
setColl=new HashSet();
for (int i=0;i<4;i++){
// Here i am adding the elements to the set.
setColl.add("SetElement"+i);
// Here i am adding the duplicate entries. But those will not be stored and all the duplicate entries will
// be regected. And boolean will be retruned. To see the same uncomment the below second line, //(1).
setColl.add("SetElement"+i);
System.out.println(setColl.add("SetElement"+i)); // (1)
}
// I am creating the Iterator, so that i can loop through the iterator and can access the elements of the set class.
Iterator it = setColl.iterator();
while(it.hasNext()){
P.p(it.next());
}
}
public static void main(
String[] args) {
SetExample obj = new SetExample();
obj.method();
}
}
-------
Let me know if you couldn't understand any thing in the code.
Thanks..