问题
Why does the method add(<T> element)
and remove(Object o)
accept different arguments?
For example in a Set<Short>
you add short elements. Why does the method remove accepts Object
? If you can't add any other data type, why would you remove other data type?
Thank you.
回答1:
add(<T> element)
: to ensure that just a T element is added.
remove(Object o)
: you can delete the T element even if it's a referenced by an Object reference.
For instance :
T t = new T();
Set<Short> set = new HashSet<Short>();
Short number = 2;
set.add(number);
Object numberObject = number;
set.remove(numberObject) // it will remove 2 from the set.
why would you remove other data type? we're not removing another data type, but we can remove data even if it is referenced by an Object reference (like in the example).
回答2:
The remove(obj)
method, removes the object such that (obj == null ? e ==null : obj.equals(e))
is true
. It's because of the equals(Object)
method, which takes an Object
, that obj
and e
doesn't have to be of the same type.
来源:https://stackoverflow.com/questions/17138241/java-add-remove-methods-of-sets