Package javas.fristdome01;
Import Org.testng.annotations.Test;
Class Person {
private String name;
private int age;
Person () {
}
Person (String name, int age) {
THIS.name = name;
This.age = age;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
public int getage () {
return age;
}
public void Setage (int.) {
This.age = age;
}
/**
* If you do not write the ToString method, the Hascode will be generated.
* ToString (); Indicates the string description of the object
*
*/
@Override
Public String toString () {
TODO auto-generated Method Stub
Return "Name:" +this.getname () + ". Age" +this.getage ();
}
@Override
public boolean equals (Object obj) {
TODO auto-generated Method Stub
if (obj instanceof person)
{
Person P = (person) obj;
if (This.getname (). Equals (P.getname ()) && (This.getage () ==p.getage ()))
{
return true;
}else
{
return false;
}
}else
{
return false;
}
}
@Override
public int hashcode () {
TODO auto-generated Method Stub
Return This.getname (). Hashcode () +this.getage ();
}
}
public class Objcetdome {
@Test
public void TST ()
{
person P1 = new Person ("Zhang Shan", 20);
System.out.println (p1); Output 16 Binary
person P2 = new Person ("Zhang Shan", 20);
System.out.println ("Hascode of the object of the P1:" +p1.hashcode ());//output is a decimal data
System.out.println ("Hascode of the object of the P1:" +p2.hashcode ());//output is a decimal data
System.out.println ("-----------------------");
System.out.println (P1 = = p2);
System.out.println ("Two objects are equal:" +p1.equals (p2));
}
}
/** Pre-condition does not override the ToString () method
* Person P1 = new Person ("Zhang Shan", 20);
System.out.println (p1);
* [Email protected]-this is Hascode
* If two objects equals the same, their hashcod are the same
* [Email protected]--output 16 binary
The hasCode1585787493 of the P1 object--The output is the decimal data
*
* equals determines whether the content is equal. The default is to determine whether Hascode want to wait
* If you override Equals, you must also override the Hashcode method
*
*
* */
=======================
Name: Zhang Shan. Age 20
The hascode:778597 of P1 objects
The hascode:778597 of P1 objects
-----------------------
False
Two objects are equal: true
Passed:tst
In Java, Equals and Hashcode also have the ToString Method learning record