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语句时一定用{}括起来,即使只有一条语句,也要括起来,既是保持代码可读性的良好习惯,也就能规避你这个手误输入的分号了。

    评论

报告相同问题?

悬赏问题

  • ¥15 C#读写EXCEL文件,不同编译
  • ¥15 如何提取csv文件中需要的列,将其整合为一篇完整文档,并进行jieba分词(语言-python)
  • ¥15 MapReduce结果输出到HBase,一直连接不上MySQL
  • ¥15 扩散模型sd.webui使用时报错“Nonetype”
  • ¥15 stm32流水灯+呼吸灯+外部中断按键
  • ¥15 将二维数组,按照假设的规定,如0/1/0 == "4",把对应列位置写成一个字符并打印输出该字符
  • ¥15 NX MCD仿真与博途通讯不了啥情况
  • ¥15 win11家庭中文版安装docker遇到Hyper-V启用失败解决办法整理
  • ¥15 gradio的web端页面格式不对的问题
  • ¥15 求大家看看Nonce如何配置