- import java.util.*;
- class Person
- {
- private String name;
- private int age;
- Person(String name,int age)
- {
- this.name = name;
- this.age = age;
- }
- public boolean equals(Object obj)
- {
- if(!(obj instanceof Person))
- return false;
- Person p = (Person)obj;
- return this.name.equals(p.name) && this.age== age;
-
- }
- public String getName()
- {
- return name;
- }
- public int getAge()
- {
- return age;
- }
- }
- class Demo
- {
- public static void main(String[] args)
- {
- ArrayList ar = new ArrayList();
- ar.add(new Person("zhangsan01",21));
- ar.add(new Person("zhangsan02",22));
- ar.add(new Person("zhangsan03",23));
- ar.add(new Person("zhangsan03",23));
- ar.add(new Person("zhangsan04",24));
- ar.add(new Person("zhangsan04",24));
- ar = show(ar);
-
- Iterator it = ar.iterator();
- while(it.hasNext())
- {
- Object obj = it.next();
- Person p = (Person)obj;
- System.out.println(p.getName()+";;;;"+p.getAge());
- }
- }
- public static ArrayList show(ArrayList ar)
- {
- ArrayList lis = new ArrayList();
-
- Iterator it = ar.iterator();
- while(it.hasNext())
- {
- Object obj =it.next();
- if (!lis.contains(obj))
- lis.add(obj);
-
- }
- return lis;
- }
- }
复制代码
我想问一下,就是说如果在,哈希值相同,元素不相同的话,是可以存入的,是吧?为什么重写了Object 类中的方法,返回一个,自己定义的int 型的值,就能保证这些 对象 哈希值 是相同的啊?大神 帮忙解释一下 |