栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

object类中equals和tostring重写,hash函数,getClass函数

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

object类中equals和tostring重写,hash函数,getClass函数

import java.util.*;

public class Main{
    public static void main(String[] args)
    {
        person staff=new person("lol");
        person man=new person("xxx");
        System.out.println(man);//默认man.toString()
        if(staff.equals(man))
        {
            System.out.println("yes");
        }else{
            System.out.println("no");
        }
    }
}

class person{
    private String name;
    public person(String name)
    {
        this.name=name;
    }
    public String getname()
    {
        return this.name;
    }
    
    public String toString()
    {
        return getClass()+" "+getname();
    }
    
    public int hashcode()
    {
        return Objects.hash(getname());
    }
    
    public boolean equals(Object otherobject)
    {
        if(this==otherobject)  return true;
        //若两者引用同一块数据区域,返回真
        if(otherobject==null)  return false;
        //若两者都为空,则返回假
        if(getClass()!=otherobject.getClass())  return false;
        //也可以用instanceof方法
        //若两者类名不相同,返回假
        var other =(person)otherobject;//将otherobject强制类型转换,否则无法使用person类的数据和方法
        return Objects.equals(this.name,other.name);
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/307024.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号