java 如何获取 HashMap 值的属性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5804762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:51:51  来源:igfitidea点击:

How to get attributes for HashMap value?

javaattributeshashmap

提问by OP2011

"my" code:

“我的”代码:

public void iterateHashmap2() {
    HashMap hashmap = this.media;
    Iterator it = hashmap.keySet().iterator();
    while (it.hasNext())
    {
        Object key = it.next();
        Object val = hashmap.get(key);
            // doesn't work..
        System.out.println(val.getAttribute);
    }
}

So my question is, how do I get the attributes that the value contains. The value is a class I made myself, which contains 4 Strings and another class I made, as attributes. (What I want to do is iterate through a hashmap and compare the String of an attribute that is stored in the value with input data.. so I need to be able to access the attributes in the values of the hashmap..hope that makes sense..)

所以我的问题是,如何获取该值包含的属性。该值是我自己创建的一个类,其中包含 4 个字符串和我创建的另一个类作为属性。(我想要做的是遍历哈希图并将存储在值中的属性的字符串与输入数据进行比较..所以我需要能够访问哈希图的值中的属性..希望感觉..)

回答by Sean Patrick Floyd

You access values in a map by providing a key:

您可以通过提供键来访问映射中的值:

// create a map
Map<String, MyObject> map = new HashMap<String, MyObject>();
// store a value
map.put("key", someObject);
// retrieve a value
MyObject someObject2 = map.get("key");

You can also use

你也可以使用

  • map.keySet()to retrieve all keys
  • map.values()to retrieve all values, without keys
  • map.entrySet()to retrieve all Mappings. Each Entry represents one key mapped to one value.
  • map.keySet()检索所有密钥
  • map.values()检索所有值,没有键
  • map.entrySet()检索所有映射。每个条目代表一个键映射到一个值。

a) In my code I use Java Generics, because that has been the standard way to do it for at least 5 years now.
b) You should consider reading The Map Interfacefrom the Java Tutorial.

a) 在我的代码中,我使用Java 泛型,因为这已经成为至少 5 年以来的标准方法。
b)你应该考虑读地图界面Java教程

回答by u290629

a): If you are using JDK1.5or higher, please use generic and enhanced loop. The code will much simpler and safer:

a): 如果您使用的是JDK1.5或更高版本,请使用通用和增强循环。代码会更简单、更安全:

 for(Map.Entry<Key, YourObj> entry: this.media.entrySet()){
    System.out.println(entry.getValue().getAttribute());
 }

b): If you have to use JDK1.4or lower, you have to cast your object: ((YourObj)val).getAttribute();

b): 如果你必须使用JDK1.4或更低版本,你必须转换你的对象:((YourObj)val).getAttribute();

回答by Stefan Kendall

Object val = hashmap.get(key);
            // doesn't work..
System.out.println(val.getAttribute());

The problem here is that Java is statically typed, which means you would need to cast valin order to access non-Object methods. You need to cast valas the type actually in the hashmap, as you're not using generics.

这里的问题是 Java 是静态类型的,这意味着您需要进行强制转换val才能访问非 Object 方法。val由于您没有使用泛型,因此您需要将其转换为哈希图中的实际类型。

MyClass val = (MyClass) hashmap.get(key);

MyClass val = (MyClass) hashmap.get(key);

回答by anubhava

Try changing this line:

尝试更改此行:

Object val = hashmap.get(key);

to this line:

到这一行:

YourClass val = (YourClass) hashmap.get(key);

Since you are getting an Object type you cannot just call your class's method without first casting it correctly.

由于您获得的是 Object 类型,因此您不能在没有首先正确转换的情况下调用您的类的方法。

Btw you should seriously consider using Java Generics

顺便说一句,您应该认真考虑使用Java 泛型

回答by Jan Zyka

You will need a cast to a your target object's type. Like:

您将需要转换为目标对象的类型。喜欢:

YourObject val = (YourObject) hashmap.get(key); 

But ...

但 ...

  • Your Map should be generic like Map<KeyClass, ValueClass>
  • There is better way to iterate over a Map:
  • 你的地图应该是通用的 Map<KeyClass, ValueClass>
  • 有更好的方法来迭代 a Map

Example:

例子:

for (Map.Entry<KeyClass, ValueClass> entry : map.entrySet()) {
    KeyClass key = entry.getKey();
    ValueClass val = entry.getValue());
} 

回答by Liv

If your question is how to cast the value mapped to the key in the HashMap why not use generics to achieve that:

如果您的问题是如何转换映射到 HashMap 中的键的值,为什么不使用泛型来实现这一点:

public void iterateHashmap2() {
    HashMap<Object,YourClass> hashmap = this.media;
    Iterator<YourClass> it = hashmap.keySet().iterator();
    while (it.hasNext())
    {
        Object key = it.next();
        YourClass val = hashmap.get(key);
            // if YourClass has a getAttribute() method then this will work
        System.out.println(val.getAttribute());
    }
}

Also note that it's always good practice to work at interface level -- so this line:

还要注意,在界面级别工作总是很好的做法——所以这一行:

    HashMap<Object,YourClass> hashmap = this.media;

should be

应该

    Map<Object,YourClass> hashmap = this.media;