Equals方法始终返回true,等于运算符始终返回false

问题描述 投票:0回答:1

我创建了一个状态类。从初始状态开始,

State state = new State(0, pkg1Location[0], pkg2Location[0], truckLocation[0], planeLocation[0], cityLocation[0]);

我要迭代直到目标状态

static State goal = new State(0, pkg1Location[5], pkg2Location[4], truckLocation[3], planeLocation[2], cityLocation[1]);

具有do ... while条件。问题是,如果我写

if(state.equals(goal)) {
            System.out.println("TRUE 1");
        }else {
            System.out.println("FALSE 1");
        }

始终返回true。否则,如果我写

if(state == goal) {
                System.out.println("TRUE 2");
            }else {
                System.out.println("FALSE 2");
            }

                  }

总是错误的。

我还在状态类中重写了equal方法,就像这样

@Override
    public boolean equals(Object o) { 

        // If the object is compared with itself then return true   
        if (o == this) { 
            return true; 
        } 

        /* Check if o is an instance of Complex or not 
          "null instanceof [type]" also returns false */
        if (!(o instanceof State)) { 
            return false; 
        } 

        // typecast o to Complex so that we can compare data members  
        State c = (State) o; 

        // Compare the data members and return accordingly  
        return stateParameter1.compareTo(c.stateParameter1) == 0
                && stateParameter2.compareTo(c.stateParameter2)== 0
                    && stateParameter3.compareTo(c.stateParameter3)== 0
                        &&stateParameter4.compareTo(c.stateParameter4) == 0
                            &&stateParameter5.compareTo(c.stateParameter5) == 0;
    } 
}

为什么会这样?

java comparison equals string-comparison
1个回答
0
投票

String比较必须使用equals方法而不是==完成,因为==运算符会比较内存中String对象的引用而不是String的内容。

    // Compare the data members and return accordingly  
    return stateParameter1.compareTo(c.stateParameter1).equals(0)
            && stateParameter2.compareTo(c.stateParameter2).equals(0)
                && stateParameter3.compareTo(c.stateParameter3).equals(0)
                    &&stateParameter4.compareTo(c.stateParameter4).equals(0)
                        &&stateParameter5.compareTo(c.stateParameter5).equals(0);
© www.soinside.com 2019 - 2024. All rights reserved.