-3
public class AccountManager {

    priavte Map accountTotals = new HashMap();
    private int retirementFund;

    public int getbalance(String accountName) {
        **Integer Total = (Integer) accountTotals.get(accountName);
        if(total == Null)
            total = Integer.valueof(0);
        return total.intValue;**
    }

    public void setBalance (string accountName, int amount) {
        accountTotals.put(accountname, Integer.valueof(amount));
    }
}

I can replace the highlighted code with two of the them to perform it:

1:

int Total = accountTotals.get(accountName);
if(total == null)
    total = 0;
return total;

2:

Integer total = accountTotals.get(accountName);
if(total == null)
    total = 0;
return total;

3:

return accountTotals.get(accountName);

Can someone tell me which two of the above 3 I should replace with the highlighted code ? And why ?

Thanks!!

Sri
  • 177
  • 2
  • 2
  • 10

2 Answers2

1

Your code should look like this:

public class AccountManager {
    private Map<String, Integer> accountTotals = new HashMap<>();
    private int retirementFund;

    public int getbalance(String accountName) {
        Integer total = accountTotals.get(accountName);
        if(total == null) {
            return 0;
        }
        return total;
    }

    public void setBalance (String accountName, int amount) {
        accountTotals.put(accountName, amount);
    }
}

Aside from many typos in the source code, here is some explanation:

  • Use the generic version of map: Map<String, Integer>. This will give you typesafety both when you put or get data from the map.
  • Unfortunately, Java generics don't work with primitive types. Therefore the map must contain boxed Integer instances.
  • On the other hand, this allows you to use the total == null condition to check whether the value is in the map or not. That's why you need to use Integer total = accountTotals.get(accountName) instead of int total = accountTotals.get(accountName);. If the value is not present, the latter would try to unbox the result of get() to store it in the int variable. But because null cannot be unboxed, you would get a NullPointerException.
  • When returning, you can simply write return total;. Even though total is of type Integer and the result type is int, Java will automatically unbox the value. Of course, you can only do this if total is not null.

Since your question was probably aimed at conversion between Integer and int, you can see that Java is doing conversions in both directions automatically (boxing: accountTotals.put(accountName, amount), unboxing: return total). You just have to keep in mind that only Integer can contain null and if you try to unbox a null value, you'll get NullPointerException.

Mifeet
  • 12,949
  • 5
  • 60
  • 108
0

int isn't allowed to be null. Integer is allowed to be null. The access from the hashmap can return a null, so the value can't be an int...

Egwor
  • 1,322
  • 9
  • 16