ArraryList的结构是数组,所以它是可以有重复元素的。你的主函数里面并一个调用学生类中equals方法。所以要去除集合中的重复元素的话可以定义一个新的集合判断学生是否是重复的。代码如下:- class Person
- {
- private String name;
- private int age;
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Person))
- return false;
- Person p=(Person)obj;
- return this.name==p.name&&this.age==p.age;
-
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getName() {
- return name;
- }
- public void setAge(int age) {
- this.age = age;
- }
- public int getAge() {
- return age;
- }
- Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- }
- public class ArraryListTest2
- {
- public static void main(String[] args)
- {
- ArrayList<Person> al=new ArrayList<Person>();
- al.add(new Person("zhangsan",21));
- al.add(new Person("zhangsan",22));//Object obj=new Person();
- al.add(new Person("zhangsan",23));
- al.add(new Person("zhangsan",21));
- al.add(new Person("zhangsan",22));
- al=method(al);
-
- //sop(al.remove(new Person("zhangsan",23)));//remove也是调用了person中的equals方法
- Iterator it=al.iterator();
- while(it.hasNext())
- {
- Person p=(Person)it.next();
- sop(p.getName()+"....."+p.getAge());
- }
-
-
-
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- public static ArrayList method(ArrayList al)
- {
- ArrayList<Object> newal=new ArrayList();
- Iterator<Object> it=al.iterator();
- while(it.hasNext())
- {
- Object obj=it.next();
- if(!newal.contains(obj))//调用的是equals方法。
- newal.add(obj);
- }
- return newal;
-
- }
-
- }
复制代码 |