0

Why Java's Collection.contains() use 'Object o' as the parameter, unlike Collection.add() which uses the generic E?

This gives rise to potential mistakes like

HashSet<Integer> hash = new HashSet();
hash.contains(1.42); //will always be false
James
  • 317
  • 2
  • 15
  • 1
    Worth noting static analysis tools like SonarQube, findbugs etc. will flag up potential errors like this for you... – Adam Jul 19 '16 at 05:26
  • To quote a comment from the accepted answer which sums it up pretty good `Actually, it's very simple! If add() took a wrong object, it would break the collection. It would contain things it's not supposed to! That is not the case for remove(), or contains().` – SomeJavaGuy Jul 19 '16 at 05:26
  • While it certainly is an error to put a bicycle into my bag of clothes it is not necessarily an error to ask "does this bag of clothes contain a bicycle" - even though the answers is always "no" there is nothing wrong in the question itself. – piet.t Jul 19 '16 at 05:42
  • @piet.t: The answer is not always no. A bicycle might be equal to a piece of clothing. – newacct Jul 19 '16 at 21:17

0 Answers0