baidu_34387489 2016-03-23 03:41 采纳率: 0%
浏览 1408

Arraylist 去重复时编写去重方法没有运行找不到错误在哪?求大神帮看一下

class Person {
private String name;
private int age;
Person (String name,int age) {
this.name = name;
this.age =age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
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;
}
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Person("tom",1));
al.add(new Person("jack",8));
al.add(new Person("jack",8));
al.add(new Person("aaron",5));
al.add(new Person("aaron",5));
al.add(new Person("lisi",8));

    al = singleName(al);

    for(Iterator<Object> it =al.iterator(); it.hasNext();) {
        Person p = (Person)it.next();
        System.out.println(p.getName()+"----"+p.getAge());
    }       
}
public static ArrayList<Object> singleName(ArrayList<Object> al) {
    ArrayList <Object> newAl= new ArrayList<Object>();
    Iterator <Object> it = al.iterator();
    while  (it.hasNext()) {
        Object obj = it.next();
        if(!newAl.contains(obj));
            newAl.add(obj);     
    }
    return newAl;   
}

}

  • 写回答

3条回答 默认 最新

  • 毕小宝 博客专家认证 2016-03-23 03:48
    关注

    singleName这个方法中,if条件后面的分号去掉,因为你加了分号,就是空语句了,后面的代码就不是if语句的内容了。
    修正如下:

        public static ArrayList<Object> singleName(ArrayList<Object> al) {
            ArrayList<Object> newAl = new ArrayList<Object>();
            Iterator<Object> it = al.iterator();
            while (it.hasNext()) {
                Object obj = it.next();
                if (!newAl.contains(obj)){
                    newAl.add(obj);
                }
            }
            return newAl;
        }
    

    这个问题很容易发现,就是格式化下代码,就能看到多出一个分号了;
    这个问题也很容易规避,就是编写代码遵循一定的规范,使用if语句时一定用{}括起来,即使只有一条语句,也要括起来,既是保持代码可读性的良好习惯,也就能规避你这个手误输入的分号了。

    评论

报告相同问题?

悬赏问题

  • ¥20 Python安装cvxpy库出问题
  • ¥15 用前端向数据库插入数据,通过debug发现数据能走到后端,但是放行之后就会提示错误
  • ¥15 python天天向上类似问题,但没有清零
  • ¥30 3天&7天&&15天&销量如何统计同一行
  • ¥30 帮我写一段可以读取LD2450数据并计算距离的Arduino代码
  • ¥15 C#调用python代码(python带有库)
  • ¥15 矩阵加法的规则是两个矩阵中对应位置的数的绝对值进行加和
  • ¥15 活动选择题。最多可以参加几个项目?
  • ¥15 飞机曲面部件如机翼,壁板等具体的孔位模型
  • ¥15 vs2019中数据导出问题