繁体   English   中英

toString方法output的解释以及toString out和hashCode output的区别

[英]Explanation of toString method output and difference between toString out and hashCode output

public class ObjectClass {
    public static void main(String[] args) {
        Demo dm = new Demo();
        Object obj = dm.getObject();
        System.out.println("Class name :: "+obj.getClass());
        System.out.println("To String " + dm.toString());
        System.out.println("HashCode "+ dm.hashCode());
    }
}

Output

    Class name :: class newTopic.Object.Demo
    To String :: newTopic.Object.Demo@2a139a55
    HashCode :: 705927765

Demo@2a139a55和hascode 705927765有什么区别

如果您查看ObjecttoString()的 Javadoc,您会看到:

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', andt he unsigned hexadecimal representation of the hash code of the object. 换句话说,此方法返回一个等于以下值的字符串:

getClass().getName() + '@' + Integer.toHexString(hashCode())

因此dm.toString()返回:

newTopic.Object.Demo      @           2a139a55

getClass().getName()  +  '@'  + Integer.toHexString(   705927765   )
                                                     dm.hashCode()

这两个是 Object class 方法。 如果你不覆盖,那么这些将被自动继承。 这里我将尝试解释 3 个方法,toString()、equals() 和 HashCode()。

  1. toString - 它有助于以字符串的形式表示 object。 (有关更多信息 - https://www.geeksforgeeks.org/object-tostring-method-in-java/go通过此链接)。

  2. equals 和 HashCode - equals 方法用于比较两个 object 的相等性,HashCode 有助于生成 object 的 hashCode。 两者一起对 HashMap 有帮助(大部分)。 要获取更多信息,请阅读 HashMap 的内部实现。 https://www.geeksforgeeks.org/internal-working-of-hashmap-java/

我希望这对你有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM