wood burning stoves 2.0*
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics(Map)" Watch "Generics(Map)" New topic
Author

Generics(Map)

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!

Yuan

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.


SCJP 6
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.

HTH

My Blog SCJP 5 SCWCD 5
Bindu Lakhanpal
Ranch Hand

Joined: Oct 17, 2008
Posts: 165

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!
Yuan
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics(Map)