今天复习集合!写了一个关于ArrayList去冲的代码!编译通过,就是出现了安全问题。
泛型该加的地方都加了,不知道哪里没加,请高手指点。- import java.util.*;
- class Demo
- {
- public static void main(String[] args)
- {
- ArrayList<Student> al = new ArrayList<Student>();
- al.add(new Student("sad1",20));
- al.add(new Student("sad3",20));
- al.add(new Student("sad1",20));
- al.add(new Student("sad4",21));
-
- al = quChong(al);
- for(Student s : al)//高级for循环,和迭代一一样的
- {
- System.out.println(s.getName()+"-"+s.getAge());
- }
- }
- public static ArrayList<Student> quChong(ArrayList<Student> al)
- {
- ArrayList<Student> newAl = new ArrayList<Student>();
- for(Iterator<Student> it = al.iterator() ; it.hasNext();)
- {
- Student s = it.next();
- if(!(newAl.contains(s)))
- {
- newAl.add(s);
- }
- }
- return newAl;
- }
- }
- class Student
- {
- private String name;
- private int age;
- Student(String name ,int age)
- {
- this.name = name;
- this.age = age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Student))
- throw new RuntimeException("数据类型错误");
- Student s = (Student)obj;
- return s.name.equals(this.name) && s.age == this.age;
- }
- }
复制代码
|