0
import java.util.Scanner;
import java.util.ArrayList;
public class Project84 {
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    ArrayList<Archive> items = new ArrayList<>();

    while (true) {
        System.out.println("Identifier? (empty will stop)");
        String id = scan.nextLine();
        if (id.equals(""))  {
            break;
        }

        System.out.println("Name? (empty will stop)");
        String name = scan.nextLine();
        if (name.equals(""))  {
            break;
        }

        Archive list = new Archive(id, name);

        if (!(items.contains(list))) {
            items.add(list);
        }
        // This above part is designed to eliminate Archives that are the same. I don't know why it doesn't work
    }
    for (Archive item:items) {
        System.out.println(item.id() + ": " + item.name());
    }

    // use the for (Objecttype dog:dogamount)
    }
}

Most of the code functions properly, up until the part where I'm trying to verify if an item contains the list and add it only if it's not on the list. I'm having problems trying to figure out why that doesn't work.

public class Archive {
private String identifier;
private String name;

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

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

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

public boolean equals(Archive obj) {
    if (obj.identifier.equals(this.identifier)) {
        return true;
    }
    return false;
}
}

For reference, this is my custom object class. The only problem I'm really encountering here is that the ArrayList stores multiple of the same objects with the same properties, when I want it to only store one of each.

  • 2
    your equals() does not override `Object`s one and is not called by the list when it compares the given Archive to list's content. that is because `Object`s equals() is defined as public boolean equals(Object obj); – Sharon Ben Asher Aug 21 '22 at 18:09
  • Have you considered using a HashSet? Using the right tool for the job makes coding much more pleasant. – MarsAtomic Aug 21 '22 at 18:11

0 Answers0