一个内存地址真的只能存放一个对象?,但HashSet中出现了两个甚至更多相同hashCode值,但是它们内容不一样,难道一个内存地址可以放几个对象?无法理解这个
- public class HashSetDome {
-
- public static void main(String[] args) {
-
-
- HashSet hs = new HashSet();
- Person p1 = new Person("a1", 11);
- Person p2 = new Person("a2", 13);
- Person p3 = new Person("a3", 13);
-
- hs.add(p1);
- hs.add(p2);
- hs.add(p3);
-
-
-
- Iterator it = hs.iterator();
-
- while(it.hasNext()){
- Person p = (Person)it.next();
- System.out.println(p.getName()+"....."+p.getAge());
- }
- }
- }
- class Person{
-
- private String name;
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- private int age;
- public Person(String name ,int age){
- this.name = name;
- this.age = age;
-
- }
-
- public int hashCode(){
-
- return 60;//地址值改为一样的了
- }
- public boolean equals(Object obj){
-
- if(!(obj instanceof Person)){
- return false;
- }
- Person p = (Person)obj;
- return this.name.equals(p.name)&&this.age == p.age;
- }
-
-
- }
复制代码 |
|