1

I have a question about the use of generic types in the Java Collections framework.

Here's a snippet of the Set interface taken from Oracle's Java Collections thread (found here):

public interface Set<E> extends Collection<E> {
    // Basic operations
    int size();
    boolean isEmpty();
    boolean contains(Object element);
    // optional
    boolean add(E element);
    // optional
    boolean remove(Object element);
    ...

My question is this: Given that Set<E> is generic with generic type parameter E, why are the contains and remove methods declared to take arguments of type Object? The add method takes an argument of type E, why don't contains and remove do the same?

Peter Littig
  • 177
  • 3

1 Answers1

-1

It is simply because of backwards compatibility to the time before generic where added to java.

This way old code still works.

MrSmith42
  • 9,961
  • 6
  • 38
  • 49
  • Thanks, MrSmith42. Do you have an example of the backwards compatibility in mind? It would be nice to see it in action. – Peter Littig Mar 01 '13 at 19:53