在Java中使用equals方法查找相等对象
想将地址数据封装在一个对象中。这样,“Person”不等于其地址,你可以进行更精细的搜索。另外,你可以通过这种方式分离问题。
我在这里写了一个示例:
import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors;
public class Person {
public static void main(String[] args) {
// what we're searching for
Address address = new Address('123 N 3rd st', 'east ohg', 'this-city');
// init
List persons = new ArrayList<>();
persons.add(new Person('Jim', '123 N 56 st', 'east ohg', 'this-city'));
persons.add(new Person('Kyle', '145 N 67th st', 'east ohg', 'this-city'));
persons.add(new Person('Sam', '12 beach av', 'east ohg', 'this-city'));
persons.add(new Person('Tracy', '123 N 3rd st', 'east ohg', 'this-city'));
persons.add(new Person('Ashley', '123 N 3rd st', 'east ohg', 'this-city'));
// search
List people = persons.stream().filter(person -> person.address.equals(address)).collect(Collectors.toList());
people.forEach(System.out::println);
}
String name;
Address address;
public Person(String name,
String addressLine1,
String addressLine2,
String city) {
this.name = name;
this.address = new Address(addressLine1,
addressLine2,
city);
}
private static final class Address {
String addressLine1;
String addressLine2;
String city;
public Address(String addressLine1, String addressLine2, String city) {
this.addressLine1 = addressLine1;
this.addressLine2 = addressLine2;
this.city = city;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Address address = (Address) o;
return Objects.equals(addressLine1, address.addressLine1) &&
Objects.equals(addressLine2, address.addressLine2) &&
Objects.equals(city, address.city);
}
@Override
public int hashCode() {
return Objects.hash(addressLine1, addressLine2, city);
}
@Override
public String toString() {
return 'Address{' +
'addressLine1='' + addressLine1 + '\'' +
', addressLine2='' + addressLine2 + '\'' +
', city='' + city + '\'' +
'}';
}
}
@Override
public String toString() {
return 'Person{' +
'name='' + name + '\'' +
', address=' + address +
'}';
}
}
赞0
踩0