Getting hashmaps

getting hashmaps problem.

I tried getting the hashmap outside the if (BookValues.containsKey(ID)) and i would always getting:

java nullpointer exception

here's the code : (let's assume this has been declared. I used Integer,Class for my hashmap)

    int targetID = BookValues.get(ID).BookID.intValue();
    String targetTitle = BookValues.get(ID).Title.toString();
    String targetAuthor= BookValues.get(ID).Author.toString();
    int targetCopies=BookValues.get(ID).Copies.intValue();

whenever i code it inside the contains key, it works but when i do it outside it runs into an error. I was thinking of getting it outside the .containsKeybecause it would make my code longer and i'm trying to save spaCan somebody explain it to me?

Upvotes: 0

Views: 50

Answers (1)

geco17
geco17

Reputation: 5294

The code

int targetID = BookValues.get(ID).BookID.intValue();
String targetTitle = BookValues.get(ID).Title.toString();
String targetAuthor= BookValues.get(ID).Author.toString();
int targetCopies=BookValues.get(ID).Copies.intValue();

has quite a few places where exceptions could be thrown.

BookValues.get(ID) will give you the object if it exists or null if it doesn't. To avoid a possible NullPointerException this line should be broken up. The following assumes your map's values are BookValue objects.

BookValue value = BookValues.get(ID);
if (value != null) {
    int targetId = value.BookID.intValue();
    String targetTitle = value.Title.toString();
    String targetAuthor = value.Author.toString();
    int copies = value.Copies.intValue();
    // rest of code here
} else {
    // TODO do something if there's no value in the map for the specified key
}

Note that in this way, you also avoid repeating the .get(ID) on .

Consider also following the java code conventions

Upvotes: 2

Related Questions