![](/img/trans.png)
[英]How can I use objects in an ArrayList to be able to add or remove them from other bit of storage Java
[英]how can I remove objects from my ArrayList that are also in other ArrayList in Java?
在我的java
代码中,我有一个Person
结构:
public class Person {
String name;
String distance;
String address;
String field1;
String field2;
}
现在,我有一个包含夫妇对象的ArrayList<Person> people
。 我还有另一个包含其他对象的ArrayList<Person> otherPeople
。
我想生成一个第3个列表,其中包含尚未在otherPeople
people
所有对象。
但是我只需要按对象的name
, distance
和address
来比较它们,而不必关心field1
和field2
的值。
我考虑过创建2 for循环:
for (Person newPerson: people) {
for (Person oldPerson: otherPeople) {
if(newPerson.getName().equals(oldPerson.getName()) &&
newPerson.getDistance().equals(oldPerson.getDistance()) &&
newPerson.getAddress().equals(oldPerson.getAddress()) {
但我不知道该如何进行,尤其是因为我无法从要迭代的列表中删除元素……您能帮我吗?
您可以覆盖Person类的equal方法吗? 然后,您将可以使用remove或removeAll方法从集合中删除人员。
class Person {
String name;
String distance;
String address;
String field1;
String field2;
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person person = (Person) o;
return Objects.equals(name, person.name) &&
Objects.equals(distance, person.distance) &&
Objects.equals(address, person.address);
}
@Override
public int hashCode() {
return Objects.hash(name, distance, address);
}
}
class Example {
public static void main(String[] args) {
Person person1 = new Person();
person1.address = "address_1";
person1.distance = "distance_1";
person1.name = "name_1";
person1.field1 = "field1_1";
person1.field2 = "field2_2";
Person person2 = new Person();
person2.address = "address_2";
person2.distance = "distance_2";
person2.name = "name_2";
person2.field1 = "field1_2";
person2.field2 = "field2_2";
ArrayList<Person> people = new ArrayList<>(Arrays.asList(person1, person2));
System.out.println(people);
ArrayList<Person> otherPeople = new ArrayList<>(Arrays.asList(person1));
people.removeAll(otherPeople);
System.out.println(people);
}
}
您可以尝试类似:
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<>();
ArrayList<Person> otherPeople = new ArrayList<>();
ArrayList<Person> peopleDistinct = new ArrayList<>(people);
peopleDistinct.removeAll(otherPeople);
}
但是首先,您必须为Person
类重新定义equals
方法。
编辑:这是一个如何覆盖equals
方法的示例:
@Override
public boolean equals(Object other) {
boolean result = false;
if (other instanceof Person) {
Person that = (Person) other;
result = (this.name == that.name && this.distance == that.distance && this.address == other.address);
}
return result;
}
注意:如果equals函数必需,则应添加field1
和field2
。
在Person类中实现equals()和hashcode()方法,并根据名称,距离,地址计算哈希码。 有关更多详细信息,您可以搜索如何编写良好的哈希函数。 请记住,在equals方法中,您编写了一个逻辑,如果两个对象的名称,距离和地址值相同,则将两个对象视为相等。 但是,请不要忘记也实现hashcod(),因为当您使用hashset和hashmap时,不实现它可能会进一步增加复杂性。
然后,按照您已经开始的方式,使用for循环比较每个人的目标。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.