I have a question. First, I declared a map:
Map<TwoIntClass, Set<Integer>> m = new HashMap<TwoIntClass, Set<Integer>>();
Now, I want to put stuff inside this map, something like
int num = 7;
m.put(new TwoIntClass(5, 3), ?? how to put num inside Set ??);
My question is, how do I put variable num inside Set.
Thanks.
Like Jack and others have suggested, you need to instantiate a concrete instance of the
Setinterface (likeHashSet), add yourintvalues in theSetand then put theSetinto yourMap. However, if you are using a custom class for yourMap‘s key, I would suggest you implement theequals()andhashCode()method of yourTwoIntClassclass to be sure that you are not creating duplicate entries inside yourMap. For example, consider this class :The output for executing it is :
As you see, they both are “equal” (i.e. they both are constructed with the same integers), but they are distinct objects with different hash codes, therefore create two entries in the map. This could lead into possible data corruption in your application. Moreover, executing this line :
map.get(new TwoIntClass(5,3)).add(3);will generate aNullPointerExceptionbecause the key (it’s hash) does not exist in the map. So, you need to implement theequals()andhashCode()methods to fix this, so anyTwoIntClassconstructed with the same integers will be considered equal. Something like :yields a more expected result of
Of course, this
hashCode()method isoversimplistic and you may need to find a yet better construct, but the bottom line is that implementing them is what I would recommend.