简体   繁体   中英

HashSet contains not working for Integer

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));

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 .

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));
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM