嗯,能编译,能运行 不过运行后的全变哈希值了 咋弄
这个好办,以下代码:就能解决问题
class Person {
private String name;
private int age;
Person(String name, int age) {
this.name = name;
this.age = 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 String getname() {
return name;
}
public int getage() {
return age;
}
}
class Arraylist3 {
public static void sop(ArrayList<Person> al) {
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i).getname() + "今年" + al.get(i).getage());
}
}
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(new Person("zhangsan1", 30));
al.add(new Person("zhangsan2", 36));
al.add(new Person("zhangsan1", 30));
al.add(new Person("zhangsan3", 35));
sop(al);
al = qcf(al);
sop(al);
}
public static ArrayList qcf(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;
}
}
希望楼主好好思考,关键代码如下:
public static void sop(ArrayList<Person> al) {
for (int i = 0; i < al.size(); i++) {
System.out.println(al.get(i).getname() + "今年" + al.get(i).getage());
}
}
希望对您有帮助。 |