then the set can't contain/remove any other type
Of course it can. Read about type erasure or cast your HashSet
to non-generic HashSet
and add an object which is not of type E
to it.
Check out this code:
Integer testInt = new Integer(3);
// First, create a generic set of strings
HashSet set = new HashSet();
set.add("abc");
// Then make it non-generic and add an integer to it
((HashSet) set).add(testInt);
// Now your set-of-strings contains an integer!
System.out.println(set); // prints: [abc, 3]
// Remove the integer
set.remove(testInt);
System.out.println(set); // prints: [abc]
The reason of this weirdness is that the information of generic types is erased in runtime and your set becomes a simple set of objects.