本帖最后由 李凤鸣 于 2013-1-8 14:18 编辑
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public boolean equals(Object obj)
- {
- System.out.println("7");
- if(!(obj instanceof Person))
- return false;
- Person p=(Person)obj;
- System.out.println(this.name+"..."+p.name);
- return this.name.equals(p.name)&&this.age==p.age;
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class ArrayListTest2
- {
- public static void main(String[] args)
- {
- ArrayList al=new ArrayList();
- al.add(new Person("lisi01",20));
- al.add(new Person("lisi02",28));
- al.add(new Person("lisi03",27));
- al.add(new Person("lisi04",26));
- al.add(new Person("lisi05",25));
- al.add(new Person("lisi06",23));
- al.add(new Person("lisi07",21));
- al.add(new Person("lisi03",27));
-
- sop("1");
- al=singleElement(al);
- sop("2");
- Iterator it=al.iterator();
- sop("3");
- while(it.hasNext())
- {
- sop("4");
- Person p=(Person)it.next();
- sop("5");
- sop(p.getName()+"::"+p.getAge());
- sop("6");
- }
- }
- public static ArrayList singleElement(ArrayList al)
- {
- //定义一个临时容器
- ArrayList newaArrayList=new ArrayList();
- Iterator iterator=al.iterator();
- while (iterator.hasNext()) {
- Object obj=iterator.next();
- if (!newaArrayList.contains(obj)) {
- newaArrayList.add(obj);
- }
-
- }
- return newaArrayList;
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 这是视频中的一个例子,重写了equals方法,视频里讲是因为contanse(Object obj) 中有 equals方法
是说这里面的equals只能比较地址么,而不是equals(Object obj)
equals(Object obj)这个方法在什么时候用
|