黑马程序员技术交流社区
标题: 关于集合的一些问题 [打印本页]
作者: 王桂丽 时间: 2012-7-26 16:08
标题: 关于集合的一些问题
/*
将自定义对象作为元素存到ArrayList集合中,并去除重复元素。
比如:存人对象。同姓名同年龄,视为同一个人。为重复元素。
思路:
1,对人描述,将数据封装进人对象。
2,定义容器,将人存入。
3,取出。
*/
import java.util.*;
class Person //定义Person类
{
private String name;//定义私有变量姓名name
private int age;//定义私有变量年龄age
Person(String name,int age)//将姓名与年龄属性赋给人
{
this.name=name;
this.age=age;
}
public boolean equals(Object obj);//覆盖父类的equals方法
{
if(!(obj instanceof Person))
return false;
Person p=(Person)obj;//将obj强转成Person类
return this.name.equals(p.name)&&this.age==p.age;
}
public String getName()//访问name的方法
{
return name;
}
public int getAge()//访问age的方法
{
return age;
}
}
class ArrayListTest2
{
public static void sop(Object obj)
{
System.out.println(obj);
}
public static void main(String[] args)
{
ArrayList a1=new ArrayList();//新建ArrayList容器,并用a1接收
a1.add(new Person("Lisi01",30));//给a1中添加对象为Person的元素
a1.add(new Person("Lisi01",30));
a1.add(new Person("Lisi02",31));
a1.add(new Person("Lisi03",32));
a1.add(new Person("Lisi03",32));
a1.add(new Person("Lisi04",37));
a1=singleElement(a1);//调用singleElement方法
Iterator it =a1.iterator();//采用迭代器方法取出元素
while(it.hasNext())//当a1中还有元素时,进行while循环
{
Object obj=it.next();
Person p=(Person)obj;
sop(p.getName()+"::"+p.getAge());
}
}
public static ArrayList singleElement(ArrayList a1)
{
ArrayList newA1=new ArrayList();
Iterator it=a1.iterator();
while(it.hasNext())
{
Object obj=it.next();
if(!newA1.contains(obj))
newA1.add(obj);
}
return newA1;
}
}
疑问:1、程序编译出错,不知错在哪里?编译结果如附件“未命名1”
2、public boolean equals(Object obj);//覆盖父类的equals方法
{
if(!(obj instanceof Person))
return false;
Person p=(Person)obj;//将obj强转成Person类
return this.name.equals(p.name)&&this.age==p.age;
}
这里的this.name指的是谁?
3、既然singleElement返回的是newA1的值,
a1=singleElement(a1);//调用singleElement方法
Iterator it =a1.iterator();//采用迭代器方法取出元素
while(it.hasNext())//当a1中还有元素时,进行while循环
{
Object obj=it.next();
Person p=(Person)obj;
sop(p.getName()+"::"+p.getAge());
}
4、a1.add(new Person("Lisi01",30));//给a1中添加对象为Person的元素
a1.add(new Person("Lisi01",30));
给ArrayList a1中添加的为什么默认的是Object类型的?不管a1.add()里添加的是什么,默认的都是Object类型吗?
迭代器里传的是否应是newA1而不是a1
Iterator it =newA1.iterator();//采用迭代器方法取出元素
-
未命名1.jpg
(48.83 KB, 下载次数: 15)
-
未命名2.jpg
(8.93 KB, 下载次数: 16)
-
未命名3.jpg
(20.92 KB, 下载次数: 15)
作者: 肖琦 时间: 2012-7-26 16:40
本帖最后由 肖琦 于 2012-7-26 16:43 编辑
- <font color="#000000" size="3" face="宋体"></font>
复制代码楼主开发时用的是ue吧,用eclipse吧,你上面是编译错误,原来你的equals方法()后跟了个“;”
看了楼主的代码,楼主是想用ArrayList实现不可以放重复的元素,思路没有问题,就是细节问题,建议开发用eclipse
作者: 王桂丽 时间: 2012-7-26 17:50
肖琦 发表于 2012-7-26 16:40 ![](static/image/common/back.gif)
楼主开发时用的是ue吧,用eclipse吧,你上面是编译错误,原来你的equals方法()后跟了个“;”看了楼主的代 ...
我用的是EditPlus,去掉“;”后可以运行了,谢谢你的意见!
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |