Java add remove methods of sets

旧时模样 提交于 2019-12-08 02:52:10

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!