用equals方法比较虚构对象的问题

时间:2020-04-26 05:06:31

标签: java object equals

我正在尝试制作一个将对象存档与Arraylist存档进行比较的程序,并仅将其添加到arraylist中(如果它不在其中,但确实很麻烦)。我尝试过修改for循环,以添加一个新的布尔值来检查是否已经存在一个相同的存档,但是似乎无法仅添加唯一的存档就可以了。任何建议将不胜感激。

import java.util.ArrayList;
import java.util.Scanner;

public class Main {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Archive> archives = new ArrayList<>();
        while (true) {
            System.out.println("Identifier? (empty will stop)");
            String identifier = scanner.nextLine();
            if (identifier.isEmpty()) {
                break;
            }
            System.out.println("Name? (empty will stop)");
            String name = scanner.nextLine();
            if (name.isEmpty()) {
                break;
            }
            Archive archive = new Archive(identifier, name);

            boolean contains = false;
            for (int i = 0; i < archives.size(); i++) {
                if (archive.equals(archives.get(i))) {
                    contains = true;
                    break;
                }
            }
            if (contains == false) {
                archives.add(archive);
            }
        }

        for (Archive i : archives) {
            System.out.println(i.getIdentifier() + ": " + i.getName());
        }
    }
}



public class Archive {

    private String identifier;
    private String name;

    public Archive(String identifier, String name) {
        this.identifier = identifier;
        this.name = name;
    }

    public String getIdentifier() {
        return this.identifier;
    }

    public String getName() {
        return this.name;
    }

    public boolean equals(Archive archive, Object compared) {

        if (compared == archive) {
            return true;
        }
        if (!(compared instanceof Archive)) {
            return false;
        }

        Archive compare = (Archive) compared;
        if (compare.getIdentifier().equals(archive.getIdentifier()) && compare.getName().equals(archive.getName())) {
            return true;
        }

        return false;
    }

}

//也刚刚意识到,我可以做的事情不是用boolean包含整个for循环

if(archives.contains(archive){
contains=true;}

1 个答案:

答案 0 :(得分:3)

equals方法的签名错误。 应该是

public boolean equals(Object compared) {
    if(compared==null || !(compared instanceof Archive)){
        return false;
    }

    Archive compare = (Archive) compared;
    if (compare.getIdentifier().equals(this.getIdentifier()) && compare.getName().equals(this.getName())) {
        return true;
    }

    return false;
}