Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics(Map)

 
Yuan Du
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 952
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 598
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Bindu Lakhanpal
Ranch Hand
Posts: 171
Flex Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 34
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right! Thank you very much!
Yuan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic