I am new to java, i know set is not allowed duplicate value but i don't know why set is not allowed duplicate value, Actually i am doing practically,
Declared one set and add duplicate value but no kind of error is occurring, no compile time error, no run time. why?
The meaning of "sets do not allow duplicate values" is that when you add a duplicate to a set, the duplicate is ignored, and the set remains unchanged. This does not lead to compile or runtime errors: duplicates are silently ignored. Set is implemented like that to avoid duplication.
A Set is a Collection that cannot contain duplicate elements.
HASHTABLE is a structure of Key value pairs.. Here what the values passed by the SET is treated as Keys of HASHTABLE Internally. keys are unique cannot be duplicated.
HashSet is an implementation of Set Interface which does not allow duplicate value. The main thing is, objects that are stored in HashSet must override equals() for check for equality, and hashCode() methods for no duplicate value are stored in our set.
A collection that contains no duplicate elements. More formally, sets contain no pair of elements e1 and e2 such that e1.equals(e2), and at most one null element. As implied by its name, this interface models the mathematical set abstraction.
See: http://docs.oracle.com/javase/7/docs/api/java/util/Set.html
In mathematics, a set is a collection of distinct objects, considered as an object in its own right.
According to the documentation of the interface, if the element does not exist it is added. Otherwise, nothing changes.
boolean add(E e):
Adds the specified element to this set if it is not already present (optional operation). If this set already contains the element, the call leaves the set unchanged and returns false.
/**
* Adds the specified element to this set if it is not already present.
* More formally, adds the specified element <tt>e</tt> to this set if
* this set contains no element <tt>e2</tt> such that
* <tt>(e==null ? e2==null : e.equals(e2))</tt>.
* If this set already contains the element, the call leaves the set
* unchanged and returns <tt>false</tt>.
*
* @param e element to be added to this set
* @return <tt>true</tt> if this set did not already contain the specified
* element
*/
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With