I have a hashMap with an arrayList as its value. I would like to use the computeIfAbsent method to efficiently create the list when a key is not in the map. Then I tried to use ArrayList::new
instead of k -> new ArrayList<Integer>()
to make the code more clear, but got "invalid capacity" error if the key is a negative number.
Map<Integer, List<Integer>> map = new HashMap<>();
map.computeIfAbsent(-4, x -> new ArrayList<Integer>());//This is OK
map.computeIfAbsent(-5, ArrayList::new);//This gives error
java.lang.IllegalArgumentException: Illegal Capacity: -5
Looks like the key is passed to the constructor. Could anyone tell me how this happens? Is it possible I can still use method reference in this case to create the arrayList?