您的位置:首页 > 其它

去除ArrayList集合中的重复自定义对象元素

2018-03-12 14:06 621 查看
本文转载至:http://blog.csdn.net/qq_36748278/article/details/76789885

要求去除ArrayList集合中重复的Student的对象(什么叫重复,所有属性值都相同叫做重复)。 

思路: 

1、创建一个新集合 

2、遍历旧集合中的每一个元素,去新集合中找这个元素,如果这个元素不存在就添加到新集合中

Student类如下:有两个成员变量name和age
public class Student {
private String name;
private int age;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}


测试类如下:
public class ListDemo {
public static void main(String[] args) {
//创建集合
ArrayList<Student> list = new ArrayList<Student>();

//创建集合元素对象
Student s1 = new Student("梨梨",21);
Student s2 = new Student("熊熊",24);
Student s3 = new Student("菜菜",10);
Student s4 = new Student("梨梨",18);
Student s5 = new Student("哈哈",25);
Student s6 = new Student("熊熊",24);
Student s7 = new Student("菜菜",10);

//把对象添加到集合中
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);

//创建一个新集合
ArrayList<Student> newList = new ArrayList<Student>();

//遍历旧集合
Iterator it = list.iterator();
while(it.hasNext()){
Student s = (Student)it.next();
if(!newList.contains(s)){
newList.add(s);
}
}

//遍历输出集合
for(int i = 0 ;i < newList.size();i++){
Student s = (Student)newList.get(i);
System.out.println(s);
}
}
}


输出结果为:
Student [name = 梨梨,age = 21]
Student [name = 熊熊,age = 24]
Student [name = 菜菜,age = 10]
Student [name = 梨梨,age = 18]
Student [name = 哈哈,age = 25]
Student [name = 熊熊,age = 24]
Student [name = 菜菜,age = 10]


看到输出结果,我们发现出错了。并没有去掉重复的对象元素。

通过查找代码错在哪里,我们可以发现可能在判断上面出了问题。判断新集合中是否存在已知元素,我们用了contains()方法。 

我们看看contains方法的源码:
public boolean contains(Object o) {
return indexOf(o) >= 0;
}
public int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++)
if (elementData[i]==null)
return i;
} else {
for (int i = 0; i < size; i++)
if (o.equals(elementData[i]))
return i;
}
return -1;
}


我们可以发现,contains()方法的底层依赖的还是equals()方法,而在Student类中没有重写equals方法,因此调用的是Object的equals方法,而Object中的equals方法比较的是地址值,而通过new Student()创建的对象他们的地址值不可能一样,因此找到了问题所在。 

要解决这问题,我们需要在Student中重写equals方法。 

因此,只需要修改一下Student方法即可。
public class Student {
private String name;
private int age;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐