The parameter of contains
and remove
cannot be restricted to E
because you should be able to give them just equal objects, which is quite useful. More precisely, the API of HashSet.remove
says:
... More formally, removes an element e such that (o==null ? e==null :
o.equals(e)), if this set contains such an element.
Object.equals
takes Object
as parameter, which is also quite useful to enable equality between different types.
Thus, to enable the more general functionality of contains
and remove
(on equivalence classes instead of only object identity), they have to take Object
as parameter.
Example:
HashSet<ArrayList<String>> set = new HashSet<ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
list.add("foo");
LinkedList<String> equalList = new LinkedList<String>();
equalList.add("foo");
set.add(list);
System.out.println(list.equals(equalList)); // prints: true
System.out.println(set.contains(equalList)); // prints: true
System.out.println(set); // prints: [[foo]]
set.remove(equalList);
System.out.println(set); // prints: [[]]