Junior
Para que servem os métodos equals() e toString() em Java?
sobes.tech IA
Resposta da IA
O método equals() é usado para comparar objetos em termos de equivalência lógica, ou seja, determina se dois objetos representam o mesmo valor ou entidade, independentemente de serem o mesmo objeto físico na memória.
O método toString() é usado para obter uma representação em string do objeto. Por padrão, ele retorna uma string que contém o nome da classe e seu código hash, mas muitas vezes é sobrescrito para fornecer uma descrição mais informativa do estado do objeto.
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; // Comparação de referências
if (o == null || getClass() != o.getClass()) return false; // Verificação de tipo e null
ExampleObject that = (ExampleObject) o; // Casting de tipo
return id == that.id && // Comparação por campos significativos
name.equals(that.name);
}
@Override
public int hashCode() {
// Sobrescrever hashCode é obrigatório ao sobrescrever 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");
// Uso de equals()
System.out.println("obj1 equals obj2: " + obj1.equals(obj2)); // true - logicamente equivalentes
System.out.println("obj1 equals obj3: " + obj1.equals(obj3)); // false - objetos diferentes
// Uso de toString()
System.out.println("obj1 toString(): " + obj1.toString()); // Mostrará a representação em string do objeto
}
}