aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes K&B SCJP6 Chapter 7- Q5 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 "K&B SCJP6 Chapter 7- Q5" Watch "K&B SCJP6 Chapter 7- Q5" New topic
Author

K&B SCJP6 Chapter 7- Q5

Richard Kuehner
Greenhorn

Joined: Apr 11, 2010
Posts: 3
Hello:

I'm working through the K & B SCJP study guide. I am completely confused by the Chapter 7 self-test, question 5. I was wondering if anybody can help.

The question begins with this code:

1. import java.util.*;
...

12. public class AccountManager{
13. private Map accountTotals = new HashMap();
14. private int retirementFund;
15.
16. public int getBalance(String accountName) {
17. Integer total = (Integer) accountTotals.get(accountName);
18. if (total == null)
19. total = Integer.valueOf(0);
20. return total.intValue();
21. }
22.
23. public void setBalance(String accountName, int amount) {
24. accountTotals.put(accountName, Integer.valueOf(amount));
25. }
26. }

The problem involves rewriting the above code with generic types, otherwise producing equivalent results. There are several code snippets, along with instructions of which original lines they should replace, and we need to figure out which ones are correct.

One of the choices (E) is to replace lines 17-20 above with the following code:

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

According to the answer key, this is a correct choice (one of them). However, when I add these lines, my code does not even compile. Here is the error message:

AccountManager.java:17 incompatible types
found : java.lang.Object
required: java.lang.Integer
Integer.total = accountTotals.get(accountName);
^
I'm pretty new to Java, but this error message actually makes complete sense to me. The way I see it HashMap get() returns an Object, and without casting the compiler will not let us brute-force this into an Integer.

Why does the book say that this answer is correct? Maybe I've been staring at this too long, and there is an obvious answer right in front of me that I'm not seeing.

Help!

Thanks in advance for your help, it is greatly appreciated

Richard
Karthik Shiraly
Ranch Hand

Joined: Apr 04, 2009
Posts: 497
    
    5
Hi,

One of the choices should be to change the Map to use generics:

Choice E is correct only if the above choice is also selected.
Richard Kuehner
Greenhorn

Joined: Apr 11, 2010
Posts: 3
I see! Choices B and E (and G) work in combination!

I wasn't thinking that one or more of these code changes were to be combined. I was making each of these code changes one at a time. Mental block...

Thanks so much.

Richard
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: K&B SCJP6 Chapter 7- Q5