我想删除重复的元素,视频里用的是ArrayList这个容器,但是我用StringBuffer为什么不对呢,我想了好久,还是无果,请大神给点建议,非常感谢!代码如下:
import java.util.ArrayList;
import java.util.Iterator;
public class PersonDemo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Person p1 = new Person("lishi1",23);
ArrayList al = new ArrayList();
al.add(p1);
al.add(new Person("lishi2",23));
al.add(new Person("lishi3",34));
al.add(new Person("lishi2",23));
al.add(new Person("lishi5",25));
al.add(new Person("lishi6",27));
StringBuffer sb = new StringBuffer();
Iterator it = al.iterator();
while(it.hasNext()){
Person p=(Person)it.next();
if(!sb.equals(p)){
sb.append(p);
}
}
System.out.println(sb.toString());
}
}
class Person{
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
|
|