How to look up for exact same objects with .contains() method in java? [duplicate]
The idea is simple I don't need to add objects that are already on the list. I guess the problem is that it creates a completely new object and it doesn't find a match with other identical objects that are already on the list(I might be completely wrong).
import java.util.Scanner;
import java.util.ArrayList;
public class archive {
private String indentifier;
private String name;
public archive(String indentifier,String name) {
this.name = name;
this.indentifier = indentifier;
}
public String toString() {
return this.indentifier + ": "+this.name;
}
public static void main(String[] args) {
ArrayList<archive> arhivs = new ArrayList<>();
Scanner scan = new Scanner(System.in);
String indentifier, name;
while(true) {
System.out.println("Indentifier? (empty will stop)");
indentifier = scan.nextLine();
if(indentifier.isEmpty()) {
break;
}
System.out.println("Name?(empty will stop)");
name = scan.nextLine();
if(name.isEmpty()) {
break;
}
archive newAr = new archive(indentifier,name);
if(arhivs.contains(newAr)) {
System.out.println("Item is on the list");
}else {
arhivs.add(newAr);
}
}
System.out.println("==Items==");
for(archive arhivi:arhivs) {
System.out.println(arhivi);
}
scan.close();
}
}
Solution 1:
Override equals
(& hashCode
)
You neglected to provide overrides of the inherited Object#equals
and Object#hashCode
methods.
The default implementation of equals
uses identity to compare, that is, "Do the two object references being compared share the same implicit memory address?".
Instead, you want to compare the contents of the two objects. So you need to write that content-comparison code in your own equals
method. And whenever overriding equals
, it is generally best to override hashCode
using the same logic.
Your IDE will assist you in writing that code. For example, in IntelliJ, see this documentation and this discussion.
This issue has been covered many times on Stack Overflow. So search to learn more.
Records
By the way, you can more briefly define your class as a record.
record Archive ( String identifier , String name ) {}
A record is appropriate when the main purpose of your class is to communicate data transparently and immutably.
The compiler implicitly creates the constructor, getters, equals
& hashCode
, and toString
methods.
👉🏾 So using a record makes your problem moot, assuming you want to compare each and every member field on the class. The equals
& hashCode
overrides are provided for you.