gpt4 book ai didi

java - 无法计算出 HashSet 的输出?

转载 作者:行者123 更新时间:2023-12-01 18:33:07 26 4
gpt4 key购买 nike

这是我的第一个类

  public class MainClass {

public static void main(String args[])
{
java.util.Set s=new java.util.HashSet();
s.add(new Integer(10));
s.add(new Integer(1));
s.add(new Integer(5));
s.add(new Integer(3));
s.add(new Integer(6));
s.add(new Integer(9));
s.add(new User("John",25));
s.add(new User("John",25));
java.util.Iterator it=s.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
}

}

这是我的第二堂课

  public class User {

String name;
int age;

public User(String name,int age)
{
System.out.println("I am in constructor");
this.name=name;
this.age=age;
}

@Override
public boolean equals(Object obj)
{
System.out.println("I am in equals");
User u=(User)obj;
if(this.age==u.age)
{
return this.name.equals(u.name);
}
else
{
return false;
}
}

@Override
public int hashCode()
{
System.out.println("I am in hash code");
return this.name.hashCode()+this.age;
}

@Override
public String toString()
{
System.out.println("I am in to String");
return String.format("Name: %s", this.name);
}
}

输出为

 I am in constructor
I am in hash code
I am in constructor
I am in hash code
I am in equals
1
I am in to String
Name: John
3
5
6
9
10

我的问题是如何比较这些元素?

最佳答案

顺序是这样的:

  1. First output is inside User constructor.
  2. Then hash is calculated to store your object inside HashSet structure, so you have an output from hashCode method
  3. It's the same as numer 1, but for the second user.
  4. It's the same as number 2, but for the second user.
  5. Because your hashCode method inside User is counted by age of the user, both users have the same hash, so equals method must be called to verify if the objects are the same. (it's because 2 objects in Java don't have to be the same even if they have the same hash code)
  6. Now you are printing all objects inside HashSet which doesn't contain any order, so you can get all the elements in random order. (keep in mind that objects inside any Set are unique)
  7. Because you overwritten toString method it prints content of the User object.

作为提示:从 1.5 版本开始,在 Java 中使用任何数据结构的原始类型都不是一个好主意。看看泛型。

关于java - 无法计算出 HashSet 的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23242548/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com