- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
- public String getName()
- {
- return this.name;
- }
- public boolean equals(Object obj)
- {
- Person p=(Person)obj;
- return this.name.equals/*这是Object类中的equals方法*/(p.name)&&this.age==p.age;
- }
- }
- class Demo
- {
- public static void main(String[] args)
- {
- ArrayList al=new ArrayList();
- al.add(new Person("zhangsan",20));
- al.add(new Person("lisi",21) );
- al.add(new Person("wangwu",25));
- al.add(new Person("zhangsan",20));
- sop(al);
- al=single(al);
- sop(al);
- }
- public static ArrayList single(ArrayList al)
- {
- ArrayList newal=new ArrayList();//新建一个集合用来存储
- ListIterator i=al.listIterator();
- while (i.hasNext())
- {
- Object obj=i.next();
- Person p=(Person)obj;
- if (!newal.contains(p))
- {
- newal.add(p);
- sop(p.getName());
- }
- }
- return newal;
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
复制代码 HashSet的存储方式时限判断存入的对象哈希地址是否相同,相同的话在用equals方法比较内容是否相同
List集合的存入方法是怎样的?谢谢
|