【问题标题】:Issue adding object to HashMap having Object as key [closed]将对象添加到以对象为键的HashMap的问题[关闭]
【发布时间】:2015-05-05 04:38:09
【问题描述】:

为什么下面的代码会出现编译错误?

class SampleClass{

}

public class DemoHashMap {

public static void main(String[] args) {
        SampleClass s1 = new SampleClass();
        SampleClass s2 = new SampleClass();

        Map<Object, Integer> counts = new HashMap<Object, Integer>();
        counts.add(s1, 1);
        counts.add(s2, 2);
    }
}

此代码不允许我将 s1 和 s2 添加到哈希图中。在计数声明中,我已指定键可以是 Object。

【问题讨论】:

标签: java


【解决方案1】:

Map 中没有add 方法。请改用put

counts.put(s1, 1);

见:- HashMap

【讨论】:

    【解决方案2】:

    需要做一些更正。

    首先Map 中没有add(),尝试使用put()

    其次,建议将SampleClass类的hashCode()equals()用作key时覆盖。

    此外,由于您使用的是泛型,因此建议将 map 声明为:

    Map&lt;SampleClass, Integer&gt; counts = new HashMap&lt;SampleClass, Integer&gt;();

    【讨论】:

      【解决方案3】:

      试试这个:

      Map<SampleClass, Integer> counts = new HashMap<SampleClass, Integer>();
      counts.put(s1, 1)
      

      【讨论】:

        猜你喜欢
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        • 2013-06-30
        • 2021-09-26
        • 1970-01-01
        • 2021-06-06
        • 1970-01-01
        • 2021-11-04
        相关资源
        最近更新 更多