3

Possible Duplicate:
Why aren’t Java Collections remove methods generic?

The Java Collection<E> interface has a contains method with the following signature:

boolean contains(Object o)

Since the interface is generic with type E shouldn't the signature be
boolean contains(E o)

to reflect that and only allow arguments of type E.

The same question can be asked regarding the remove(Object o) method

Community
  • 1
  • 1
Jonathan
  • 1,349
  • 1
  • 10
  • 20
  • 2
    may be it was added before generic took birth in java world – jmj Oct 25 '12 at 00:03
  • Looking at the [Collection JavaDoc](http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#contains(java.lang.Object)), it looks like the method is there from Java 1.2, were generics didn't exist yet in Java language. – Luiggi Mendoza Oct 25 '12 at 00:07
  • This question has been asked and answered many times before: [Why does Java Map take an untyped parameter for the get and remove methods?](http://stackoverflow.com/questions/4269147/why-does-java-mapk-v-take-an-untyped-parameter-for-the-get-and-remove-methods) and [Why aren't Java Collections remove methods generic?](http://stackoverflow.com/questions/104799/why-arent-java-collections-remove-methods-generic) – Daniel Pryden Oct 25 '12 at 00:08
  • Thanks, Daniel, for the reference. This is exactly what I needed. – Jonathan Oct 25 '12 at 00:31

1 Answers1

4

The contains and remove methods accept any object because the they accept (and can succeed with) objects that might not be instances of E. The contract for contains is:

returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e))

Note that o need not actually be an object in the collection; it must merely pass the equals test.

The same idea goes for remove.

See also this thread, where it is pointed out that making contains and remove generic would have broken a lot of existing, perfectly valid code.

Community
  • 1
  • 1
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521