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 age) {
this.age = age;
}
/**
* 如果不从写tostring方法就会生成hascode
* toString();表示对象的字符串描述
*
*/
@Override
public String toString() {
// TODO Auto-generated method stub
return "姓名:"+this.getName() + ".年龄"+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("张山",20);
System.out.println(p1); //输出16进制
Person p2 = new Person("张山",20);
System.out.println("p1的对象的hasCode:"+p1.hashCode());//输出是十进制数据
System.out.println("p1的对象的hasCode:"+p2.hashCode());//输出是十进制数据
System.out.println("-----------------------");
System.out.println(p1 == p2);
System.out.println("两个对象是否相等:"+p1.equals(p2));
}
}
/**前置条件不重写toString()方法
* Person p1 = new Person("张山",20);
System.out.println(p1);
* javas.fristdome01.Person@5e853265 --这是hascode
* 如果两个对象equals相同,他们的hashcod是相同的
* javas.fristdome01.Person@5e853265 --输出16进制
p1的对象的hasCode1585787493 --输出是十进制数据
*
* equals 判断内容是否相等 ..默认是判断hasCode是否想等
* 如果重写equals,必须还有重写hashCode方法
*
*
* */
=======================
姓名:张山.年龄20
p1的对象的hasCode:778597
p1的对象的hasCode:778597
-----------------------
false
两个对象是否相等:true
PASSED: tst