第一部分:
//创建学生类
public class Student {
//成员变量
private String name;
private int age;
//构造方法
public Student(){
super();
}
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 o) {
if (this == o) return true;
if (!(o instanceof Student)) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
第二部分:
public class Array {
public static void main(String[] args){
//创建集合对象
ArrayList list = new ArrayList();
//创建学生对象
Student s1 = new Student("苏有朋",38);
Student s2 = new Student("林志颖",40);
Student s3 = new Student("蔡依林",35);
Student s4 = new Student("林志颖",40);
Student s5 = new Student("苏有朋",38);
Student s6 = new Student("张无忌",28);
Student s7 = new Student("周芷若",18);
//添加到集合
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
list.add(s6);
list.add(s7);
//创建新的集合
ArrayList list1 = new ArrayList();
//遍历旧的集合
Iterator it = list.iterator();
while (it.hasNext()){
Student s = (Student) it.next();
if (!list1.contains(s)){
list1.add(s);
}
}
//遍历新的集合
for (int x=0;x<list1.size();x++){
Student s = (Student)list1.get(x);
System.out.println(s.getName()+"-----"+s.getAge());
}
}
}