简体   繁体   English

从HashMap返回一个元素

[英]Returning an element from the HashMap

So I'm new at Java, and have been struggling with it all semester. 所以我是Java的新手,整个学期都在为此苦苦挣扎。 In my current assignment we are working with HashMap. 在当前的工作中,我们正在使用HashMap。 I need to get getAlbum. 我需要获取getAlbum。 Return an Album from the HashMap if it exists, or null otherwise. 从HashMap返回一个相册(如果存在),否则返回null。 @oaram albumName the name of the album to return @return an Album or null @oaram albumName要返回的相册名称@返回相册或返回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. 我感觉我的代码中有太多的albumName。 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;
    }

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. 如果找不到匹配项,则地图将返回null。
As per the HashMap API : 根据HashMap API

Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key. 返回指定键所映射到的值;如果此映射不包含键的映射关系,则返回null。

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. 另外,作为旁注和根据PShemo,切勿使用==比较字符串,因为==比较一个对象引用是否与另一个对象引用相同,这在大多数情况下都不会让您感兴趣。 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)) 因此请使用if (string1.equals(string2))if string1.equalsIgnoreCase(string2))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM