我有一个问题。首先,我声明了一张 map :
Map<TwoIntClass, Set<Integer>> m = new HashMap<TwoIntClass, Set<Integer>>();
现在,我想把东西放在这张 map 里,比如
int num = 7;
m.put(new TwoIntClass(5, 3), ?? how to put num inside Set ??);
我的问题是,如何将变量 num 放入 Set 中。 谢谢。
最佳答案
赞Jack和其他人建议,您需要实例化 Set
接口(interface)的具体实例(如 HashSet
),将您的 int
值添加到 Set
,然后将 Set
放入您的 Map
中。但是,如果您为 Map
的键使用自定义类,我建议您实现 equals()
和 hashCode()
TwoIntClass
类的方法,以确保您不会在 Map
中创建重复条目。例如,考虑这个类:
public class TwoIntClass {
private int i1;
private int i2;
public TwoIntClass(int i1, int i2) {
this.i1 = i1;
this.i2 = i2;
}
static public void main(String...args) {
Map<TwoIntClass, Set<Integer>> map = new HashMap<TwoIntClass, Set<Integer>>();
Set<Integer> dataset = new HashSet<Integer>();
dataset.add(1);
dataset.add(2);
TwoIntClass i1 = new TwoIntClass(5, 3);
TwoIntClass i2 = new TwoIntClass(5, 3);
map.put(i1, dataset);
map.put(i2, dataset);
System.out.println( i1.hashCode() + " = " + i2.hashCode() + " == " + i2.equals(i2) + " > map count = " + map.size() );
TwoIntClass i3 = new TwoIntClass(5, 3);
System.out.println("Looking for TwoIntClass(5,3)... " + map.containsKey(i3) );
}
}
执行它的输出是:
1476323068 = 535746438 == false > map count = 2
Looking for TwoIntClass(5,3)... false
如您所见,它们都是“相等的”(即它们都是用相同的整数构造的),但它们是具有不同哈希码的不同对象,因此在映射中创建了两个条目。这可能会导致应用程序中的数据损坏。此外,执行此行:map.get(new TwoIntClass(5,3)).add(3);
将生成一个 NullPointerException
,因为键(它是哈希)会不存在于 map 中。因此,您需要实现 equals()
和 hashCode()
方法来解决此问题,因此任何使用相同整数构造的 TwoIntClass
都将是视为平等。像这样的东西:
@Override
public boolean equals(Object obj) {
if (!(obj instanceof TwoIntClass)) {
return false;
}
TwoIntClass other = (TwoIntClass) obj;
return (other.i1 == this.i1) && (other.i2 == this.i2);
}
@Override
public int hashCode() {
//return TwoIntClass.class.hashCode() | i1 | (i2 << 16);
// better implementation based on the String class
int hash = TwoIntClass.class.hashCode();
hash = (hash * 31) + i1;
hash = (hash * 31) + i2;
return hash;
}
产生更符合预期的结果
1476323071 = 1476323071 == true > map count = 1
Looking for TwoIntClass(5,3)... true
当然,这个hashCode()
方法过度 过于简单,您可能还需要找到一个better construct ,但最重要的是,我建议实现它们。
关于java - 在 Map 中设置 <Integer>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3867333/