本帖最后由 马林贺 于 2012-6-5 23:48 编辑
- import java.util.ArrayList;
- import java.util.Iterator;
- //创建对象类
- class Prerson {
- private String name;
- private int age;
- // 构造函数
- Prerson(String name, int age) {
- this.name = name;
- this.age = age;
- }
- // 覆写Object类中的equals方法
- public boolean equals(Object obj) {
- if (!(obj instanceof Prerson)) {
- return false;
- }
- Prerson pobj = (Prerson) obj;
- return this.name.equals(pobj.name) && this.age == pobj.age;
- }
- // 获取姓名的方法
- public String getName() {
- return name;
- }
- // 获取年龄的方法
- public int getAge() {
- return age;
- }
- }
- class ArrayListTest {
- // 去重复方法
- public static ArrayList removeRepeat(ArrayList arr) {
- ArrayList list = new ArrayList();
- Iterator it = arr.iterator();
- while (it.hasNext()) {
- Object obj = it.next();
- if (!list.contains(obj)) {
- list.add(obj);
- }
- }
- return list;
- }
- public static void main(String[] args) {
- ArrayList arr = new ArrayList();
- arr.add(new Prerson("小李01", 40));
- arr.add(new Prerson("小李02", 42));
- arr.add(new Prerson("小李03", 42));
- arr.add(new Prerson("小李04", 40));
- Iterator it = arr.iterator();
- while (it.hasNext()) {
- <STRONG> /* if (it.next() instanceof Prerson) */</STRONG>{
- Prerson p = (Prerson) it.next();
- System.out.println(p.getName() + "......" + p.getAge());
- }
- }
- System.out
- .println("--------------------------华丽分割线---------------------------");
- ArrayList list = removeRepeat(arr);
- Iterator iter = list.iterator();
- while (iter.hasNext()) {
- <STRONG> if (iter.next() instanceof Prerson)</STRONG> {
- Prerson p = (Prerson) iter.next();
- System.out.println(p.getName() + "......" + p.getAge());
- }
- }
- }
- }</P>
- <P style="LINE-HEIGHT: 30px; TEXT-INDENT: 2em"></P>
复制代码 1. 为什么我只是覆写了Object中的equals()怎么会自己调用,解释一下,看视频没有弄懂
2. 我代码加粗的部分,加与不加怎么回事两个运行结果,求解释,不是去除重复的方法造成的
if (iter.next() instanceof Prerson)
|
|