Inconsistent arguments in ArrayList methods

In the ArrayList API, add () takes an argument of type general parameters, but contains () and indexOf () takes arguments of type Object .

public class ArrayList<E> ...{ public boolean add(E e); public boolean contains(Object o); public int indexOf(Object o); .... } 

Java Doc for ArrayList

So I'm just wondering if I need to do something with Generics or create consistency?

I looked at Openjdk but could not find any specific reason for this.

+4
source share
2 answers

What the API says is:

  • You cannot add() anything that is not E ;
  • You, however, are allowed to look for things that are not E (but this can be compared to an instance of E ).

Consider the following example:

 public class Main { public static class Key { private final int k; public Key(int k) { this.k = k; } @Override public boolean equals(Object obj) { if (!(obj instanceof Key)) { return false; } Key rhs = (Key)obj; return k == rhs.k; } @Override public int hashCode() { //... return 0; } } public static class Data extends Key { private final int d; public Data(int k, int d) { super(k); this.d = d; } } public static void main(String[] args) { List<Data> l = new ArrayList<Data>(); l.add(new Data(123, 456)); l.add(new Data(42, 24)); System.out.println(l.contains(new Key(789))); System.out.println(l.contains(new Key(123))); System.out.println(l.contains(new Key(42))); } } 

The last three lines will not compile if contains() was limited to accepting Data .

+10
source
+3
source

All Articles