File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics(Map) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics(Map)" Watch "Generics(Map)" New topic


Yuan Du
Ranch Hand

Joined: Nov 20, 2008
Posts: 34
Source: KB book ch7 Question 8

Hello Everyone,
I have a question about Generics with Map.

A. Replace line 13 with
private Map<String, int> accountTotals = new HashMap<String, int>();
B. Replace line 13 with
private Map<String, Integer> accountTotals = new HashMap<String, Integer>();
C. Replace line 13 with
private Map<String><Integer>> accountTotals = new HashMap<String><Integer>>();
D. Replace lines 17–20 with
int total = accountTotals.get(accountName);
if (total == null) total = 0;
return total;
E. Replace lines 17–20 with
Integer total = accountTotals.get(accountName);
if (total == null) total = 0;
return total;
F. Replace lines 17–20 with
return accountTotals.get(accountName);
G. Replace line 24 with
accountTotals.put(accountName, amount);

The anwsers are B,E,G

I can't unterstand why E is legal.
I think it won't compile with E. because map.get(object) returns an object and this object cannot be referenced by an Integer.
Could someone explain it?

Thank you!


Punit Singh
Ranch Hand

Joined: Oct 16, 2008
Posts: 952
But now your Map definition after option B will be this one :

So its accountTotals.get(accountName) method will return Integer not Object.

Himanshu Gupta
Ranch Hand

Joined: Aug 18, 2008
Posts: 598

The question is
This class is to be updated to make use of appropriate generic types, with no changes in
behavior (for better or worse). Which of these steps could be performed? (Choose three.)

The answer is the combination of all three options. Don't take them individually.

The line

makes clear that what will go and what will come out so there is no need of casting.


My Blog SCJP 5 SCWCD 5
Bindu Lakhanpal
Ranch Hand

Joined: Oct 17, 2008
Posts: 171

Replacing 17-20 with option in E will work, but it is not nessasary to replace them with anything. It is not absolutely nessasary.
Yuan Du
Ranch Hand

Joined: Nov 20, 2008
Posts: 34
You are right! Thank you very much!
I agree. Here's the link:
subject: Generics(Map)
jQuery in Action, 3rd edition