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;
}
}
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语句时一定用{}括起来,即使只有一条语句,也要括起来,既是保持代码可读性的良好习惯,也就能规避你这个手误输入的分号了。
public static ArrayList singleName(ArrayList al) {
ArrayList newAl= new ArrayList();
Iterator it = al.iterator();
while (it.hasNext()) {
Object obj = it.next();
if(!newAl.contains(obj)); //把这行的 ; 号去掉
newAl.add(obj);
}
return newAl;
}
用set集合就可以不用去重了,,