Java 等于烦我

Java's equals bugging me

我在使用 equals 时遇到问题,让我先在此处添加代码:

Operateur o = new Operateur(nom, age, sexe, grade, role);
for(Operateur op : Membre.getOperateurs()){
  if(o.equals((Object)op)){
    already_exists = true;
    break;
  }
}

if(already_exists){
  ret = ">Can't create it : already exists";
  Membre.removeLast();
  o.finalize();
}else{
  ret = ">Created it";
}

在这里,我检查新的 Operateur 是否只是旧的副本(Membre.getOperateurs 让我得到 Membre 的所有实际实例的列表 Operateur).

我的问题是,当我 运行 这段代码时,如果我的 Operateur 是全新的,它看起来已经存在(他不应该,因为他是全新的)。

例如,当我创建第一个 Operateur 时,它会将其评估为已存在的副本。

如:

import cmd.*;
import matrice.*;
import persona.*;
import non_grata.non.*;
import non_grata.grata.*;
//all above is importing packages to use all classes required


public class Debug{
  public static void out(String s){
    System.out.println(s);
  }//handy

  public static void main(String[] args){
    Membre.init();//Membre.membre = new ArrayList<Membre>();
    Personnel.init();//Personnel.membre = new ArrayList<Membre>();
    Vaisseau.init();//Vaisseau.vaisseaux = new ArrayList<Vaisseau>();
    MatrixCmd cmd = new MatrixCmd();//Create the command parser

    String parser_input = "afficherMembres";//get some input
    String parser_output = cmd.execCommand(parser_input);//process it
    out(parser_output);//use it
    //empty list, correct since we only initialized it

    parser_input = "newOPsion mikebike 10 o string string";
    parser_output = cmd.execCommand(parser_input);
    out(parser_output);
    //outputs ">Impossible de créer cet Opérateur : Il existe déjà" which it shouldn't
    //since there are no other Operateur and this is only
    //given as output when it founds a similar Operateur

    parser_input = "afficherMembres";
    parser_output = cmd.execCommand(parser_input);
    out(parser_output);
    //outputs an empty list, meaning that there are no Membre created
    //and therefore no Operateur

    parser_input = "newOPsion mikebke 8 f tring sring";//command that will trigger the bit of code above
    parser_output = cmd.execCommand(parser_input);
    out(parser_output);
    //outputs">Impossible de créer cet Opérateur : Il existe déjà" which it shouldn't
  }
}

更改 return super.equals((Object)o) && this.role==o.role;Object.equals 测试 reference 身份(您知道 Object 是唯一实例)。另外,不要使用 == 来比较引用类型(如 String)。我想你想要

return this.role.equals(o.role);