Junior
Kādiem mērķiem Java valodā tiek izmantotas metodes equals() un toString() ?
sobes.tech AI
Atbilde no AI
equals() metode tiek naudojamas objektu salīdzināšanai, lai noteiktu, vai divi objekti pārstāv to pašu vērtību vai būtību, neatkarīgi no tā, vai tie ir fiziski tas pats objekts atmiņā.
toString() metode tiek izmantota objekta teksta pārstāvja iegūšanai. Parasti tas atgriež klases nosaukumu un tās hash kodu, bet bieži tas tiek pārrakstīts, lai sniegtu informatīvāku objekta stāvokļa aprakstu.
public class ExampleObject {
private int id;
private String name;
public ExampleObject(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true; // saites salīdzināšana
if (o == null || getClass() != o.getClass()) return false; // tipu un null pārbaude
ExampleObject that = (ExampleObject) o; // tipu pārveidošana
return id == that.id && // nozīmīgo lauku salīdzināšana
name.equals(that.name);
}
@Override
public int hashCode() {
// hashCode pārrakstīšana ir obligāta kopā ar equals
return Objects.hash(id, name);
}
@Override
public String toString() {
return "ExampleObject{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public static void main(String[] args) {
ExampleObject obj1 = new ExampleObject(1, "Test");
ExampleObject obj2 = new ExampleObject(1, "Test");
ExampleObject obj3 = new ExampleObject(2, "Another");
// `equals()` izmantošana
System.out.println("obj1 equals obj2: " + obj1.equals(obj2)); // patiesa - loģiski ekvivalenti
System.out.println("obj1 equals obj3: " + obj1.equals(obj3)); // nepatiesa - dažādi objekti
// `toString()` izmantošana
System.out.println("obj1 toString(): " + obj1.toString()); // objekta teksta pārstāvja
}
}