【问题标题】:put and get function missing from HashMap in JavaJava 中的 HashMap 中缺少 put 和 get 函数
【发布时间】:2018-09-29 09:38:29
【问题描述】:

我有一个用 Java 创建的 HashMap,它有一个字符串作为键,一个自定义类作为值,定义如下:

HashMap<String,xyz> test = new HashMap<String,xyz>();

xyz的类定义为:

public class xyz {
    String a;
    String b;
    String c;

    xyz(String a,  String b,  String c ){
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

现在,当我尝试从 hashMap 中检索值时,我无法使用 get 方法。使用的代码如下:

xyz temp = test.get("a"); // This is not working

但是,如果我只使用字符串作为键和值来创建 hashmap,我就会得到 mehtod。对于为什么会发生这种情况以及我能做些什么,我们将不胜感激。

我有 java 版本“1.8.0_172”,我使用的是 Netbeans 8.2

【问题讨论】:

  • 定义“不工作”
  • 你是如何存储你试图检索的值的?
  • tpcg.io/f4GcWp 为我工作。
  • 你在导入java.util.HashMap吗?您是否导入了不同的 HashMap 类?你在同一个包上还有另一个名为HashMap的类吗?
  • 发布一个小而完整的程序来演示您的问题,它将帮助我们调试问题。

标签: java data-structures hashmap


【解决方案1】:
public class TestHashMap {

public static void main(String[] args) {
    HashMap<String,xyz> test = new HashMap<String,xyz>();
    xyz x = new xyz("a", "b","c");
    test.put("a", x);
    System.out.println(test.get("a"));

}

}

当然,它可以运行良好。结果出来了

xyz@53d8d10a

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-29
    • 1970-01-01
    • 1970-01-01
    • 2020-10-11
    相关资源
    最近更新 更多