I have following code. Why contains & remove returns false?
Map<Integer, String> p = new TreeMap();
p.put(1, "w");
p.put(2, "x");
p.put(3, "y");
p.put(4, "z");
System.out.println(p);// {1=w, 2=x, 3=y, 4=z}
Set s = p.entrySet();
System.out.println(s);// [1=w, 2=x, 3=y, 4=z]
System.out.println(s.contains(1));//false
System.out.println(s.remove(1));//false
System.out.println(p);// {1=w, 2=x, 3=y, 4=z}
System.out.println(s);// [1=w, 2=x, 3=y, 4=z]
The
entrySet()returns aSetofMap.Entryinstances. So your lookup fails, as objects of typeMap.Entry<Integer, String>can never be equal to instances ofInteger.You should pay attention to the generic signatures, i.e.
If you want to process keys instead of entries, you have to use
keySet()instead:For completeness, note
Map’s 3rd collection view, thevalues(). Depending on the actual operation, choosing the right view can simplify your operation dramatically.