本帖最后由 王亚飞 于 2013-7-3 11:53 编辑
- //ArrayList打印自定义对象,并且去除重复元素
- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- Person(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 Person))
- return false;
- Person p = (Person)obj;
- return this.name.equals(p.name)&&this.age == p.age;
- }
- }
- class UserDefind {
- public static void main(String[] args) {
- ArrayList al = new ArrayList();
- al.add(new Person("张三",15));
- al.add(new Person("张si",56));
- al.add(new Person("张si",56));
- al.add(new Person("张wu",87));
- al.add(new Person("张liu",38));
- al.add(new Person("张liu",38));
- al.add(new Person("张qi",45));
- al = method(al);//.............................就是行,报错不兼容的类型
- Iterator it = al.iterator();
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getName()+"--"+p.getAge());
- }
- }
- public static List method(ArrayList al){
- ArrayList newal = new ArrayList();
- Iterator lit = al.iterator();
- while(lit.hasNext()){
- Object obj = lit.next();
- if(!newal.contains(obj))
- newal.add(obj);
- }
- return newal;
- }
- }
复制代码 38行不兼容的类型.....怎么会出现这个错误,修改方法 |