It's not a secret anymore!
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

K&B SCJP6 Chapter 7- Q5

Richard Kuehner

Joined: Apr 11, 2010
Posts: 3

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;
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. }
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: incompatible types
found : java.lang.Object
required: java.lang.Integer = 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.


Thanks in advance for your help, it is greatly appreciated

Karthik Shiraly

Joined: Apr 04, 2009
Posts: 874


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

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.

I agree. Here's the link:
subject: K&B SCJP6 Chapter 7- Q5
It's not a secret anymore!