It is said that those structures which implement Set interface do not allow duplicate elements. I just want to know, what do they mean by duplicate? Duplicate in terms of the values? Or in terms of objects. for example, I can开发者_运维百科 add two Integer object of same value. I can also add the same object twice. What do they mean by duplicate? When will it throw an exception?
Duplicate means as explained in another post a.equals(b)
, which implies a.hashCode()==b.hashCode()
.
However, when you add duplicate element, there will be no exception, simply it won't be added twice.
The definition of equality depends on the container. Usually it's the .equals()/.hashCode() relationship, but there are some containers that use identity for equality.
In java.util
Collections, duplicate means that a.equals(b)
and that should imply that a.hashcode()==b.hashcode()
As per the Javadocs; it means any two elements wherein e1.equals(e2)
returns true are treated as duplicate elements. Different set implementations use different strategies for storing elements; HashSet
makes use of the hashCode
of objects whereas TreeSet
relies on the natural ordering (Comparable
interface) or a custom Comparator
.
Fiver and Alvin gave good answers because "aps" is saying that he can add two of the same integers and objects but not get any compiler error or runtime exception which is true.
If you add these objects like you say and then run some code like
System.out.println(theSetYouMade.size());
and then you will see that it did not add those duplicates you were talking of.
obj1
is duplicate of obj2
if obj1.equals(obj2)
returns true. So as you can see, the definition of equal really depends on the implementation of equals.
You can write a set say, DistincObjectSet where duplicate means obj1==obj2
Another example is you can have EmployeeSet where duplicate means obj1.employeeNo == obj2.employeeNo, in this case you should overwrite the equals() method in Employee class to compare the employee numbers.
The design of the Set API says you you attempt to add duplicate element, the add() method should return false instead of throwing Exception.
精彩评论