gpt4 book ai didi

java - 比较 double map

转载 作者:行者123 更新时间:2023-12-02 13:05:43 25 4
gpt4 key购买 nike

我有一个Map<Integer,Double>作为一个字段。我需要实现equals()对于该给定的类。

如何使用容差比较 double 值。

最佳答案

public class Foo {
Map<Integer, Double> data;

public Map<Integer, Double> getData() {
return data;
}

public void setData(Map<Integer, Double> data) {
this.data = data;
}

@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (!(o instanceof Foo))
return false;
Foo foo = (Foo) o;
if (this.data.size() != foo.getData().size())
return false;

Set<Integer> keySet1 = data.keySet();
Set<Integer> keySet2 = foo.getData().keySet();
// keys should same
if (keySet1.containsAll(keySet2) && keySet2.containsAll(keySet1)) {
// for the same key, the values are close
for (Integer key : keySet1) {
if (!isEntryEqual(data.get(key), foo.getData().get(key))) {
return false;
}
}
return true;
}


return false;
}

// also need to override the hashCode method


@Override
public int hashCode() {
List<Integer> keys = new ArrayList<Integer>(this.data.keySet());
return Objects.hash(keys);
}

public static final Double PRECISION = 0.0001;

private static boolean isEntryEqual(Double d1, Double d2) {
return d1 - d2 < PRECISION;
}
}

关于java - 比较 double map ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44154318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com