我正在尝试创建一个将对象存档与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;}
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;
}