本帖最后由 徐升2013 于 2013-4-4 10:27 编辑
代码很多:我标记颜色的部分看下就可以了,代码为了实现的目的是去掉类集中的重复元素,但是始终达不到自己想要的效果,也没发现错在哪里了,求助
代码如下:
public class Test1 {
public static void main(String[] args) {
ArrayList per = new ArrayList();
per.add(new Person("张三01", 20));
per.add(new Person("张三02", 21));
per.add(new Person("张三01", 20));
per.add(new Person("张三03", 22));
per.add(new Person("张三03", 22));
per.add(new Person("张三01", 20));
Person p = new Person("王五",20);
per.add(p);
sop(per);
per = singleElement(per);
sop(per);
}
public static void sop(Collection co) {
Iterator it = co.iterator();
Person p;
if (it.hasNext()) {
p = (Person) it.next();
System.out.print("姓名:" + p.getName() + "----->年龄:" + p.getAge());
}
}
public static ArrayList singleElement(Collection arr) {
ArrayList temp = new ArrayList();
Iterator it = arr.iterator();
while (it.hasNext()) {
Person p = (Person) it.next();
if (!temp.contains(p)){
temp.add(p);
}
}
return temp;
}
}
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) {
try {
if (obj instanceof Person) {
Person p = (Person) obj;
if (this.name.equals(p.getName()) && this.age == p.getAge())
return true;
}
return false;
} catch (Exception e) {
System.out.println("输出参数有误");
throw new RuntimeException();
}
}
}
|