4

I don't understand why the contains is not working (in fact if I had passed in custom class I could have revisited my hascode and equals method but this is Integer). So instead of contains what can I use? Please help.

Set<Integer> st = new HashSet<>();
st.add(12);
Set<Integer> st1 = new HashSet<>();
st1.add(12);
System.out.println(st.contains(st1));
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
Hari Rao
  • 2,990
  • 3
  • 21
  • 34
  • The confusion is caused by the `contains` method expecting an `Object`, and not an `Integer`. So the root cause is related to this one: http://stackoverflow.com/questions/104799/why-arent-java-collections-remove-methods-generic – Marco13 Dec 18 '15 at 14:44
  • `st.contains(st1)` checks is `st` contains the object `st1` (wich is `Set`), but you just add `12` to it, not `st1` – liquid_code Dec 18 '15 at 14:46

2 Answers2

8

st.contains(st1) returns false, because the type of st1 (Set<Integer>) is not the same as the type of the elements in st (which is Integer).

You can, however, use the Set#containsAll(Collection<?>) method:

System.out.println(st.containsAll(st1));

which will check if the elements of st1 are present in st.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
5

st1 is a HashSet not an Integer.

try it with that code and you will see it works:

Set<Integer> st = new HashSet<>();
st.add(12);
System.out.println(st.contains(12));

or

public static void main(String[] args) {
    Set<Integer> st = new HashSet<>();
    st.add(12);
    Set<Integer> st1 = new HashSet<>();
    st1.add(12);
    System.out.println(st.containsAll(st1));
  }
nano_nano
  • 12,351
  • 8
  • 55
  • 83