黑马程序员技术交流社区
标题:
ArrayList去除重复元素失败?
[打印本页]
作者:
feng0606
时间:
2015-9-11 23:13
标题:
ArrayList去除重复元素失败?
import java.util.*;
public class ArrayListTest2 {
public static void main(String[] args) {
ArrayList<Person> al = new ArrayList<Person>();
al.add(new Person("lisi01",20));
al.add(new Person("lisi02",21));
al.add(new Person("lisi03",22));
al.add(new Person("lisi04",23));
al.add(new Person("lisi04",23));
singleElements(al);
Iterator<Person> it = al.iterator();
while(it.hasNext())
{
Person p = it.next();
System.out.println(p.getName()+"---"+p.getAge());
}
}
public static ArrayList<Person> singleElements(ArrayList<Person> al)
{
ArrayList<Person> newAl = new ArrayList<Person>();
Iterator<Person> it = newAl.iterator();
while(it.hasNext())
{
Person p =it.next();
if(!(newAl.contains(p)))
newAl.add(p);
}
return newAl;
}
}
class Person
{
private int age;
private String name;
public Person(String name,int age) {
super();
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
throw new RuntimeException("对象错误");
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
复制代码
为什么运行以后两个lisi都还在?求解?
作者:
lion_good
时间:
2015-9-12 06:43
两个错误
1 . 16行
2 . 29行
import java.util.*;
public class ArrayListTest2 {
public static void main(String[] args) {
ArrayList<Person> al = new ArrayList<Person>();
al.add(new Person("lisi01",20));
al.add(new Person("lisi02",21));
al.add(new Person("lisi03",22));
al.add(new Person("lisi04",23));
al.add(new Person("lisi04",23));
al=singleElements(al);
Iterator<Person> it = al.iterator();
while(it.hasNext())
{
Person p = it.next();
System.out.println(p.getName()+"---"+p.getAge());
}
}
public static ArrayList<Person> singleElements(ArrayList<Person> al)
{
ArrayList<Person> newAl = new ArrayList<Person>();
Iterator<Person> it = al.iterator();
while(it.hasNext())
{
Person p =it.next();
if(!(newAl.contains(p)))
newAl.add(p);
}
return newAl;
}
}
class Person
{
private int age;
private String name;
public Person(String name,int age) {
super();
this.name = name;
this.age = age;
}
@Override
public boolean equals(Object obj)
{
if(!(obj instanceof Person))
throw new RuntimeException("对象错误");
Person p = (Person)obj;
return this.name.equals(p.name) && this.age == p.age;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
复制代码
作者:
Java_EE
时间:
2015-9-12 07:44
顶一个,
作者:
feng0606
时间:
2015-9-12 11:07
lion_good 发表于 2015-9-12 06:43
两个错误
1 . 16行
2 . 29行
谢谢啊,确实是这两处的错误.
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2