Friday, August 6, 2010

Generics: AccountManager,java

Courtesy of SCJP Sun® Certified Programmer for Java™ 6 Study Guide Exam (310-065) (9780071591065)
Chapter 7, Question 5

Modified code


When compiling this code, the following note appears:

Note: AccountManager.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
After compiling with the -Xlint flag, the following warning appears:

AccountManager.java:14: warning: [unchecked] unchecked call to put(K,V) as a member of the raw type java.util.Map
     accountTotals.put(accountName, Integer.valueOf(amount));
 
To make this code type-safe and eliminate these warnings, we are asked to updated this class to make use of appropriate generic types. Multiple choices of code are given and a combination of these three can be used to update this class.

A. Replace line 2 with

private Map<String, int> accountTotals = new HashMap<String, int>();

B. Replace line 2 with

private Map<String, Integer> accountTotals = new HashMap<String, Integer>();

C. Replace line 2 with

private Map<String<Integer>> accountTotals = new HashMap<String<Integer>>();

D. Replace lines 8–11 with

int total = accountTotals.get(accountName);

if (total == null) total = 0;
return total;

E. Replace lines 8–11 with
Integer total = accountTotals.get(accountName);

if (total == null) total = 0;
return total;

F. Replace lines 8–11 with

return accountTotals.get(accountName);

G. Replace line 14 with

accountTotals.put(accountName, amount);

H. Replace line 14 with

accountTotals.put(accountName, amount.intValue());

Choices B, E, and G are correct

Reasons why other choices are NOT correct:

A. Cannot use a primitive type as a type parameter

private Map<String, int> accountTotals = new HashMap<String, int>();

C. Map takes two type parameters separated by a comma

private Map<String<Integer>> accountTotals = new HashMap<String<Integer>>();

D. int cannot autobox to a null. Since total was declared as an int, compiler will output:

AccountManager.java:16: incomparable types: int and <nulltype>
                    if(total==null)total=0;

F. null cannot unbox to 0. Even though code compiles and run, when you include input, you will see that an account with null balance (i.e. if (total == null)) will not be unboxed to 0, which the function getBalance() needs to return.

H. cannot autobox a primitive just by trying to invoke a method with it

accountTotals.put(accountName, amount.intValue());

No comments:

Post a Comment