Suppose we have a HashMap:

Map<Integer, Integer> stash = new HashMap<>(); 

elements of type int are put in the stash for both the key and value. Now, let's say we need to work with these values: divide some int into them. Those. so be it :

  int amount; ... for (Map.Entry stashEnrty : stash.enrtySet()) { amount = amount / (int) stashEntry.getKey(); } 

Suppose there are many such places in the code, and it is necessary to cast int to many times. Are there ways to avoid this? The key and value are added values ​​that are spars from String through Integer.parseInt ()

  • And if ... just do not put (int) ? .-. Autounboxing not working? - D-side

1 answer 1

Like this?

 for(Map.Entry<Integer, Integer> e : stash.entrySet()){ amount = amount / e.getKey(); } 
  • The fact is that in Key and value, values ​​are thrown, which were spars from String via Integer.parseInt () - lounah
  • So what? You have a stash defined as Map<Integer, Integer> stash , which means that all its Map.Entry will be Map.Entry<Integer, Integer> , not Map.Entry<Object, Object> , Integer.parseInt always returns int , or falls if not able to spar. - iksuy
  • Integer.parseInt () returns Integer, which is why if you remove the key key to (int), the compiler will swear and give the error "'/' can not be applied to 'int' and 'Object'" - lounah
  • 2
    This will be in the case of your code, in the case of the code given in my answer, everything will be fine, provided that you have declared the stash exactly as stated in the question code. It is not necessary to Integer to int , it is done automatically. - iksuy
  • Thank you so much! Now I figure out what's what, thanks again - lounah