Zdravím, jsem s Javou teprve v začátcích a prosím o radu. Chci metodou equals porovnat dva objekty, které jsou však "poskládány" z ještě dalších objektů. Jeden objekt se dědí, ale na druhý je pouze odkázáno referenční proměnnou.
public abstract class ObjectsMethod {
public static abstract class Person {
protected String name;
protected String surName;
protected String title;
public Person(String name, String surName, String title) {
super();
this.name = name;
this.surName = surName;
this.title = title;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof Person) {
Person p = (Person) obj;
return (this.name == p.name && this.surName == p.surName);
}
return false;
}
public int hashCode(){
return (name == null ? 11 : name.hashCode()) ^ (surName == null ? 17 : name.hashCode());
}
}
public static abstract class Address {
protected String city;
protected String street;
protected int number;
public Address(String city, String street, int number) {
super();
this.city = city;
this.street = street;
this.number = number;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof Address) {
Address a = (Address) obj;
return (this.city == a.city && this.street == a.street && this.number == a.number);
}
return false;
}
public int hashCode(){
return (city == null ? 11 : city.hashCode()) ^ (street == null ? 17 : city.hashCode()) ^ (number*31);
}
}
public static abstract class PersonAddress extends Address {
protected Person person;
public PersonAddress(Person person, Address address) {
super(address.city, address.street, address.number);
this.person = person;
}
@Override
public boolean equals(Object obj){
if (person == null) return false;
if (obj instanceof PersonAddress){
PersonAddress pa = (PersonAddress) obj;
return (this.city == pa.city && this.street == pa.street && this.number == pa.number); // + ještě udělat porovnání té osoby, jenže tam nevím, jak dostat ten odkaz na třídu Person.
}
return false;
}
public int hashCode(){
return (city == null ? 11 : city.hashCode()) ^ (street == null ? 17 : city.hashCode()) ^ (number*31) ^ ((person == null) ? 0 : person.hashCode());
}
}
}
Moc děkuju za jakýkoliv příspěvěk