[Java] Object class

What is the Object class?

toString method

//Implemented toString method in Person class
public class Person {
  private String firstName;
  private String lastName;
  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  @Override
  //Select the fields that characterize the class and string
  public String toString() {
    return String.format("she is,%s %s.",
        this.lastName, this.firstName);
  }
  //Make it available to individual getters
  public String getLastName() {
    return this.lastName;
  }
  public String getFirstName() {
    return this.firstName;
  }
}
public class ToStringBasic {
  public static void main(String[] args) {
    var p = new Person("Eilish", "Billie");
    System.out.println(p); //She is Billie Eilish.
  }
}

equals method

//firstName/Implement equals method in Person class of lastName field
public class Person {
  private String firstName;
  private String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  //Equivalent if both first and last name are equal
  @Override
  public boolean equals(Object obj) {
    //Judgment of identity
    if (this == obj) {
      return true;
    }
    //Judgment of equivalence
    //Type check with instanceof and type cast(Downcast)
    if (obj instanceof Person) {
      var p  = (Person)obj;
      //Judge field equivalence(String class equals method)
      return this.firstName.equals(p.firstName) &&
          this.lastName.equals(p.lastName);
    }
    //False if the type of argument obj is different
    return false;
  }
}

Rules to follow with equals

//Problematic code that violates symmetry
public class BusinessPerson extends Person {
  private String department;

//Department comparison added
  public BusinessPerson(String firstName, String lastName, String department) {
    super(firstName, lastName);
    this.department = department;
  }

  @Override
  public boolean equals(Object obj) {
    //identity
    if (this == obj) {
      return true;
    }
    //Equivalence
    if (obj instanceof BusinessPerson) {
      var bp = (BusinessPerson)obj;
      return super.equals(bp) &&
          this.department.equals(bp.department);
    }
    return false;
  }
}
public class EqualsBasic {
  public static void main(String[] args) {
    var p = new Person("Yumi", "Matsutoya");
    var bp = new BusinessPerson("Yumi", "Matsutoya", "Composer");
    System.out.println(p.equals(bp));  //true
    System.out.println(bp.equals(p));  //false
  }
}
//Problematic code that causes transitive violations
public class BusinessPerson extends Person {
  private String department;

  public BusinessPerson(String firstName, String lastName, String department) {
    super(firstName, lastName);
    this.department = department;
  }

  @Override
  public boolean equals(Object obj) {
    if (this == obj) {
      return true;
    }

    if (obj instanceof Person) {
      //For BusinessPerson type Compare all fields
      if (obj instanceof BusinessPerson) {
        var bp  = (BusinessPerson)obj;
        return super.equals(bp) &&
            this.department.equals(bp.department);
      //Person type ignores department field and compares
      } else {
        return super.equals(obj);
      }
    }
    return false;
  }
}
public class EqualsBasic {
  public static void main(String[] args) {
    var p = new Person("Yumi", "Matsutoya");
    var bp1 = new BusinessPerson("Yumi", "Matsutoya", "Composer"); 
    var bp2 = new BusinessPerson("Yumi", "Matsutoya", "singer");
    System.out.println(bp1.equals(p)); //true
    System.out.println(p.equals(bp1)); //true
    System.out.println(p.equals(bp2)); //true
    System.out.println(bp1.equals(bp2)); //false Transitive violation!
  }
}

Get hash value of object

public class ObjectHash {
  private boolean boolValue;
  private int intValue;
  private long longValue;
  private float floatValue;
  private double doubleValue;
  private String stringValue;
  @Override
  public int hashCode() {
    final int prime = 31;
    int result = 1;

    //The following calculation using the hash value
    //hash = result*31^(n) + v_1*31^(n-1) +..+ v_n
    //v_1~v_n is the int value of the field
    //n is the number of fields
    result = prime * result + (boolValue ? 1231 : 1237);
    long temp;
    //The return value of the doubleToLongBits method is a long type
    temp = Double.doubleToLongBits(doubleValue);
    result = prime * result + (int) (temp ^ (temp >>> 32));
    result = prime * result + Float.floatToIntBits(floatValue);
    result = prime * result + intValue;
    result = prime * result + (int) (longValue ^ (longValue >>> 32));
    result = prime * result + ((stringValue == null) ? 0 : stringValue.hashCode());
    return result;
  }
  @Override
  public boolean equals(Object obj) {
    if (this == obj)
      return true;
    if (obj == null)
      return false;
    if (getClass() != obj.getClass())
      return false;
    ObjectHash other = (ObjectHash) obj;
    if (boolValue != other.boolValue)
      return false;
    if (Double.doubleToLongBits(doubleValue) != Double.doubleToLongBits(other.doubleValue))
      return false;
    if (Float.floatToIntBits(floatValue) != Float.floatToIntBits(other.floatValue))
      return false;
    if (intValue != other.intValue)
      return false;
    if (longValue != other.longValue)
      return false;
    if (stringValue == null) {
      if (other.stringValue != null)
        return false;
    } else if (!stringValue.equals(other.stringValue))
      return false;
    return true;
  }
}

Compare objects

//Example of implementing compareTo method in Person class
//<Person>Object is compared
//Arrange in lexicographic order of surnames
public class Person implements Comparable<Person> {
  private String firstNameKana;
  private String lastNameKana;

  public Person(String firstNameKana, String lastNameKana) {
    this.firstNameKana = firstNameKana;
    this.lastNameKana = lastNameKana;
  }
  //Judgment of size by surname and first name kana
  @Override
  //At first`lastNameKana field`Big and small comparison
  public int compareTo(Person o) {
    //If equal`firstNameKana field`Big and small comparison
    if (this.lastNameKana.equals(o.lastNameKana)) {
      return this.firstNameKana.compareTo(o.firstNameKana);
    } else {
      return this.lastNameKana.compareTo(o.lastNameKana);
    }
  }

  @Override
  public String toString() {
    return this.lastNameKana + " " + this.firstNameKana;
  }
}
import java.util.Arrays;
import java.util.Arrays;

public class CompareBasic {
    public static void main(String[] args) {
        var data = new Person[] {
                new Person("Harry", "Potter"),
                new Person("Ron", "Weasley"),
                new Person("Hermione", "Granger"),
                new Person("Albus", "Dumbledore"),
                new Person("Severus", "Snape"),
                new Person("Serius", "Black"),
        };
        Arrays.sort(data);
        System.out.println(Arrays.toString(data));
        //[Black Serius, Dumbledore Albus, Granger Hermione, Potter Harry, Snape Severus, Weasley Ron]
    }
}

Duplicate object

//Implement Cloneable interface to explicitly allow replication
public class Person implements Cloneable {
  private String firstName;
  private String lastName;

  public Person(String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  //Match the return value to the Person type instead of the original Object, and save the trouble of casting on the user side
  @Override
  public Person clone() {
    Person p = null;
    try {
      //Call the clone method of the Object class
      p = (Person)super.clone();
    } catch (CloneNotSupportedException e) {
      throw new AssertionError();
    }
    return p;
  }

  @Override
  public String toString() {
    return this.lastName + this.firstName;
  }
}

Copy if the field contains a variable type

public class Person implements Cloneable {
  private String firstName;
  private String lastName;
  private String[] memos;

  public Person(String firstName, String lastName, String[] memos) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.memos = memos;
  }

  @Override
  public Person clone() {
    Person p = null;
    try {
      p = (Person) super.clone();
      //Explicitly duplicate the array object by calling the clone method of the corresponding field
      p.memos = this.memos.clone();
    } catch (CloneNotSupportedException e) {
      throw new AssertionError();
    }
    return p;
  }

  @Override
  public String toString() {
    return  String.format("%s%s(%s)",
        this.lastName, this.firstName, this.memos[1]);
  }
}

Recommended Posts

[Java] Object class
Java class methods
[Java] Class inheritance
java Scanner class
java (abstract class)
[Java] Nested class
Java anonymous class
About Java class
[java] abstract class
Java local class
About class division (Java)
JAVA object mapping library
Java object size feeling
Java inner class review
Java class type field
Java programming (class method)
About Java String class
Java programming (class structure)
About java abstract class
Java starting from beginner, class declaration / object generation
Java memo (standard class) substring
Java tips --StaticUtility class modifier
Java memo (standard class) length
[Implementation] Java Process class notes
About Java class loader types
How to use java class
[Java] Comparator of Collection class
Java class definition and instantiation
Muscle Java Object Oriented Day 1
Java
Summary of Java Math class
[Java] What is class inheritance?
About Java class variables class methods
Java
[Java] Object operation of ArrayList class (AOJ ④ Inversion of sequence)
[Java basics] What is Class?
[Jackson] JSON ⇔ object conversion class
Create an immutable class with JAVA
Muscle Java Object Oriented Day 2 ~ Inheritance ~
Why are class variables needed? [Java]
Call Kotlin's sealed class from Java
[Java] Object-oriented syntax --class method / argument
Various methods of Java String class
How to disassemble Java class files
Kotlin Class to send to Java developers
[Effective Java] Remove obsolete object references
StringBuffer and StringBuilder Class in Java
How to decompile java class files
[Java] How to use LinkedHashMap class
java (use class type for field)
Java source code reading java.lang.Math class
How to use class methods [Java]
[Java] How to use Math class
[Java] Private field access restrictions are not per object but per class
[Java] Wrapper that executes private method of object from outside class
Java learning (0)
Studying Java ―― 3
[Java] array
What is a class in Java language (3 /?)
[Java] Annotation
[Java] Module