相关疑难解决方法(0)

HashSet'add'方法调用何时等于?

我在HashSet比较中做了这个测试而equals 没有被调用

当farAway = false时,我想考虑等于(检查两个点距离的函数)

完全可编译的代码,你可以测试它,并告诉为什么在这个例子中没有调用equals.

public class TestClass{
     static class Posicion
    {
        private int x;
        private int y;

        @Override
        public boolean equals(Object obj) {
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            final Posicion other = (Posicion) obj;
            if ( farAway(this.x, other.x, this.y, other.y,5)){   
                return false;
            } 
            return true;
        }

        @Override
        public int hashCode() {
            int hash = 7; hash = 59 * hash + this.x; hash = 59 * …
Run Code Online (Sandbox Code Playgroud)

java comparison equals hashset

9
推荐指数
2
解决办法
1万
查看次数

Java HashMap没有从key获得价值

当我试图从具有一条记录的hashmap中获取错误时,我一直变为空.最后我用以下方式测试它:

Iterator<Position> it = pieces.keySet().iterator();
    while (it.hasNext()){
        System.out.println("object from key >> " + pieces.get(it.next()));
    }
    Iterator<Piece> itt = pieces.values().iterator();
    while (itt.hasNext()){
        System.out.println("direct object >> " + itt.next().getPosition());
    }
Run Code Online (Sandbox Code Playgroud)

我得到的输出是:

object from key >> null
direct object >> application.Position@37
Run Code Online (Sandbox Code Playgroud)

我已经显示的代码被使用,因为它之间没有任何其他东西.

关于位置对象,我重写了hashCode()函数,以根据Position类的值返回hashCode.因此,当对象中的变量发生变化时,HashCode会发生变化.上面的代码在位置对象的值更改之前很有效.但是一旦我改变了,我就会通过密钥获得空值.

java hash dictionary hashmap hashcode

0
推荐指数
1
解决办法
132
查看次数

标签 统计

java ×2

comparison ×1

dictionary ×1

equals ×1

hash ×1

hashcode ×1

hashmap ×1

hashset ×1