java基础—Objcet中的equals方法重写



package mytest;

public class Test1

{

	public static void main(String[] args) 
	{
		Person p1 = new Person(20);
		Person p2 = new Person(30);
		System.out.println(p1.equals(p2));//false
		
	}

}
class Person
{
	private int age;
	Person(int age)
	{
		this.age = age;
	}
	}
	

重写equals方法后:


package mytest;

public class Test1

{

	public static void main(String[] args) 
	{
		Person p1 = new Person(20);
		Person p2 = new Person(20);
		
		System.out.println(p1.equals(p2));//true
		
	}

}
class Person
{
	private int age;
	Person(int age)
	{
		this.age = age;
	}
	
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Person))
		{
			throw new ClassCastException("类型错误");
		}
		Person p = (Person)obj;
		
		return this.age==p.age;
	}
	
	}
	

Objcet 类的toString方法  默认的返回的内容是“对象所属的类名  和 对象的哈希值”

package mytest;

public class Test1

{

	public static void main(String[] args) 
	{
		Person p1 = new Person(20);
		Person p2 = new Person(20);
		
		System.out.println(p1.equals(p2));//true
		System.out.println(p1.toString());//mytest.Person@37
		System.out.println(p2.toString());//mytest.Person@37
		
	}

}
class Person
{
	private int age;
	Person(int age)
	{
		this.age = age;
	}
	
	public boolean equals(Object obj)
	{
		if(!(obj instanceof Person))
		{
			throw new ClassCastException("类型错误");
		}
		Person p = (Person)obj;
		
		return this.age==p.age;
	}
	public int hashCode()
	{
		return 55;
	}
	
	}
	



早起的年轻人 CSDN认证博客专家 移动开发 项目管理 Java
只要用心去做,每一件事情还是有可能成功的,当然成功是没有界限的,只不过是达到自己心里的那个目标,公众号:我的大前端生涯,一个爱喝茶的程序员,通常会搞搞SpringBoot 、Herbinate、Mybatiys、Android、iOS、Flutter、Vue、小程序等.
©️2020 CSDN 皮肤主题: 代码科技 设计师:Amelia_0503 返回首页