Вопрос

Here is my first Class

  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());
    }
   }

   }

Here is my second class

  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);
   }
   }

The output is

 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

My question is how are these elements being compared?

Это было полезно?

Решение 2

Every object inherits default implementations of hashCode() and equals() from java.lang.Object. That's why every object can be used in a hash-based collection.

The implementations of those two functions in Object are obviously very basic but ensure the contract of hashCode() and equals() is fulfilled, specifically the a.equals(b) ==> a.hashCode() == b.hashCode() statement.

Другие советы

That's the order:

  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.

As a hint: it's not a very good idea to use raw type of any data structure in Java since 1.5 version. Have a look at generics.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top