1. 實(shí)現(xiàn)方式
思路:采用的方式和去除字符串中重復(fù)值一樣概荷。
1>:創(chuàng)建一個(gè)新的集合;
2>:然后遍歷舊的集合碌燕,獲取舊集合中的每一個(gè)元素乍赫;
3>:然后判斷:如果新集合中不包含該元素,就添加陆蟆;
4>:然后遍歷新集合就可以;
2. 實(shí)現(xiàn)過程遇到的問題
如果直接按照和去除字符串中重復(fù)值代碼一樣去做惋增,不能達(dá)到去除重復(fù)對象的效果叠殷,必須在自定義對象 Student對象中重新equals()方法即可,直接用快捷鍵生成即可诈皿;
3. 具體代碼如下
1>:自定義對象Student類如下:
/**
* Email: 2185134304@qq.com
* Created by Novate 2018/5/29 15:33
* Version 1.0
* Params:
* Description: 自定義 Student對象類林束,并且重新equals()方法
*/
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = 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 object) {
if (this == object) return true;
if (object == null || getClass() != object.getClass()) return false;
Student student = (Student) object;
if (age != student.age) return false;
return name.equals(student.name);
}
@Override
public int hashCode() {
int result = name.hashCode();
result = 31 * result + age;
return result;
}
}
2>:造一個(gè)新的集合像棘,遍歷舊的集合,獲取舊集合中每一個(gè)元素壶冒,判斷新集合中是否包含該元素缕题,如果不包含,就添加胖腾;
/**
* 去除自定義對象的重復(fù)值
*/
private static void arrayListTest() {
// 創(chuàng)建集合 ArrayList對象
ArrayList<Student> arrayList = new ArrayList<>() ;
// 創(chuàng)建元素
Student s1 = new Student("王子文", 28);
Student s2 = new Student("林心如", 22);
Student s3 = new Student("林志玲", 20);
Student s4 = new Student("林憶蓮", 18);
Student s5 = new Student("王子文", 18);
Student s6 = new Student("王子文", 28);
// 添加元素
arrayList.add(s1) ;
arrayList.add(s2) ;
arrayList.add(s3) ;
arrayList.add(s4) ;
arrayList.add(s5) ;
arrayList.add(s6) ;
// 采用方式就是:新建一個(gè)集合烟零,遍歷舊的集合,獲取舊集合中每一個(gè)元素咸作,然后判斷如果新集合中不包含元素锨阿,就添加,然后遍歷新集合就可以
ArrayList<Student> newArrayList = new ArrayList<Student>() ;
// 遍歷舊的集合
for (int i = 0; i < arrayList.size(); i++) {
// 獲取舊集合中所有元素
Student s = arrayList.get(i);
// 判斷:如果新集合中不包含舊集合中的元素记罚,就添加
if (!newArrayList.contains(s)){
newArrayList.add(s) ;
}
}
// 遍歷新的集合
for (int i = 0; i < newArrayList.size(); i++) {
Student student = newArrayList.get(i);
System.out.println(student.getName() + "---" + student.getAge());
/*輸出結(jié)果:
王子文---28
林心如---22
林志玲---20
林憶蓮---18
王子文---18*/
}
}