How to implement element mapping in java?

I am from C ++ - background and just started Java today. Say I have a class with multiple data members. For instance:

public class Person {
    //Constructors/Destructor
    public Person(String strFirstName, String strLastName) {
        m_strFirstName = strFirstName;
        m_strLastName = strLastName;
        m_strFullName = m_strFirstName + m_strLastName;
    }

    //Getters
    public String GetFullName() { return m_strFullName; }
    public String GetFirstName() { return m_strFirstName; }
    public String GetLastName() { return m_strLastName; }

    //Private Data Members
    private String m_strFirstName;
    private String m_strLastName;
    private String m_strFullName;
}

Now let's say that I do this:

Person john = new Person("john", "doe");
Person johndoe = new Person("john", "doe");
if (john == johndoe) {
    System.out.println("They are Equal");
} else {
    System.out.println("They are NOT Equal");
}

Here is the result: "They are NOT equal." I understand this is due to the fact that Java compares links (memory addresses), and since they are different places in memory, the test fails. I read that Java does not support operator overloading, so I cannot overload the == operator, so is there a method that I would override to implement my method comparison? The object.equals method looked promising, but I read that this is a bad practice and does not cancel this one.

UPDATE: , , - ! , , . , , , , Java!

+3
2

:

if (john.equals(johndoe)) {
  ...
}

equals() :

public class Person {
  private String firstName;
  private String lastName;
  private String fullName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.fullName = firstName + lastName;
  }

  public String getFirstName() { return firstName; }
  public String getLastName() { return lastName; }
  public String getFullName() { return fullName; }

  @Override
  public boolean equals(Object ob) {
    if (ob == null) return false;
    if (ob.getClass() != getClass()) return false;
    Person other = (Person)ob;
    if (!firstName.equals(other.firstName)) return false;
    if (!lastName.equals(other.lastName)) return false;
    if (!(fullName.equals(other.fullName)) return false;
    return true;
  }

  @Override
  public int hashCode() {
    return firstName.hashCode() ^ lastName.hashCode() ^ fullName.hashCode();
  }
}

:

  • Java, ++. Java- Java. Java, ;
  • Java equals/hashCode, , , - .
+6

, ? equals ( hashCode) Java. . hashCode Java?.

+2

Source: https://habr.com/ru/post/1729515/


All Articles