//建一个学生类
package M8.D18;
public class Student {
private String name;
private int age;
public Student(){}
public Student(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
return "姓名:"+this.name+"年龄:"+this.age;
}
//重写equals方法
@Override
public boolean equals(Object obj) {
if(this==obj)
return true;
if(obj==null)//传进来的参数不能为空
return false;
if(!(obj instanceof Student)){//如果传来的参数不是当前类的实例
return false;
}
Student student=(Student)obj;
if(student.getName().equals(this.name)){
if(student.getAge()==this.age){
return true;
}else{
return false;
}
}else{
return false;
}
}
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;
}
}
//2.建一个Test类
public class Test {
public static void main(String[] args) {
f2();
}
public static void f2(){
/*将一个集合中重复的元素删除*/
//新建一个集合1
List olist=new ArrayList();
//在集合1中添加元素,使其有重复的元素
olist.add(new Student("悟空",357));
olist.add(new Student("悟净",55));
olist.add(new Student("悟能",37));
olist.add(new Student("唐僧",27));
olist.add(new Student("唐僧",27));
//再建一个集合,用于存储无重复的元素
List newlist=new ArrayList();
//对老的集合进行迭代,将其没有重复的元素放入新的集合中
Iterator oldi=olist.iterator();
while (oldi.hasNext()){
Student student=(Student)oldi.next();
if(!newlist.contains(student)){//在源代码中要调用类的equals方法,在student中重写了equals方法
newlist.add(student);
}
}
//对新的集合进行迭代,输出
Iterator newi=newlist.iterator();
while (newi.hasNext()){
System.out.println(newi.next());
}
}
}