Reputation: 9
So I'm new at Java, and have been struggling with it all semester. In my current assignment we are working with HashMap. I need to get getAlbum. Return an Album from the HashMap if it exists, or null otherwise. @oaram albumName the name of the album to return @return an Album or null
Here's what I currently have. Not very confident about my answer. Any tips would be greatly appreciated. I have a feeling I have one too many albumName in the code. So confused. I know it's not difficult. Thanks
public Album getAlbum(String albumName)
{
if(albumName == albumName)
return albumName;
else
if(albumName == null)
return null;
}
Upvotes: 0
Views: 58
Reputation: 285401
Note, this will always be true:
if(albumName == albumName) {
and so is never helpful.
Use the map to get what you want:
// assuming a HashMap<String, Album> called map
public getAlbum (String albumName) {
return map.get(albumName);
}
The map will return null if no match is found.
As per the HashMap API:
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.
Also as a side note and as per PShemo, never use ==
to compare Strings since ==
compares if one object reference is the same as another, something that doesn't interest you in most situations. When comparing Strings you usually want to know if the two Strings have the same chars in the same order. so use if (string1.equals(string2))
or if string1.equalsIgnoreCase(string2))
Upvotes: 3