java toString 方法是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15551358/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:01:41  来源:igfitidea点击:

How does the toString method work?

java

提问by danilojara123

//I have been trying to understand the to string how it works and what is its main function, but I am having trouble. Like in the following examaple. What exactly does the toString method do?

//我一直试图了解 to 字符串的工作原理以及它的主要功能是什么,但我遇到了麻烦。就像下面的例子。toString 方法究竟做了什么?

public class Item {

    private String name;
    private int price;
    private int qty;

    public Item() {

    }

    public Item(String n, int p, int q){
        this.name=n;
        this.price=p;
        this.qty=q;
    }

    public String getName() {
        return name;
    }

    public int getPrice() {
        return price;
    }

    public int getQty() {
        return qty;
    }

    public String toString() {
        return name +": $" + price+":" + qty;
    }

回答by PermGenError

The purpose to toStringis clearly documented in the API:

API 中清楚地记录了toString的目的:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

返回对象的字符串表示形式。通常,toString 方法会返回一个“以文本方式表示”此对象的字符串。结果应该是一个简洁但信息丰富的表示,易于人们阅读。建议所有子类都覆盖此方法。

Object#toString() will produce:

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 `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

Object 类的 toString 方法返回一个字符串,该字符串由对象是其实例的类的名称、at 符号字符“@”和对象哈希码的无符号十六进制表示组成。换句话说,此方法返回一个等于以下值的字符串:

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

If you override toString in your class call to default Object#toString() will be replaced by yourclass#toString().In your current code If you try to print Item instance the output will be of format:

如果您在类调用中覆盖 toString,则默认 Object#toString() 将被替换为 yourclass#toString()。在您当前的代码中,如果您尝试打印 Item 实例,则输出将采用以下格式:

name +": $" + price+":" + qty;

回答by Igor

toStringis typically a user-friendly/readable String representation of the object. You can use it for debugging, logging, or to display information to the end-user/client.

toString通常是对象的用户友好/可读字符串表示形式。您可以将其用于调试、记录或向最终用户/客户端显示信息。

Here is a short tutorialdiscussing how and when to use toString.

这是一个简短的教程,讨论如何以及何时使用 toString。

回答by Ivaylo Strandjev

The toString is the function called whenever java needs the string representation of an object of your class. For instance if you call System.out.println(a);where a is of typeItem, the value returned by toStringwill be displayed. This method is part of Objectand so every java object has some default implementation of it. Still in many cases it is not informative enough and its better to override it.

toString 是每当 java 需要类的对象的字符串表示时调用的函数。例如,如果您调用System.out.println(a);where a is of type ItemtoString则将显示返回的值。这个方法是一部分,Object所以每个 java 对象都有它的一些默认实现。在许多情况下,它的信息量还不够,最好覆盖它。

回答by Rawkode

toStringprovides a Stringrepresentation of an Object

toString提供了一个String表示Object

public class Person {
    private String firstName;
    private String lastName;

    private Person(String firstName, String lastName) {
         this.firstName = firstName;
         this.lastName = lastName;
    }

    public String getName() {
        return this.firstName + " " + this.lastName;
    }

    public String toString() {
        return this.firstName + " " + this.lastName;
    }
}

Imagine this class and the following calls:

想象一下这个类和以下调用:

System.out.println(aPerson.getName());

Our toStringmethods means we can simply do:

我们的toString方法意味着我们可以简单地做到:

System.out.println(aPerson);

回答by CodeBlind

I'd like to think of toString()as a convenience function. Whenever you do something like:

我想将其toString()视为一种便利功能。每当您执行以下操作时:

MyObject m = ...//
System.err.println(m);

println(m)is actually calling m.toString()to get a human-readable representation of the object. It is inherent to every Object, so you can always override it to have it return a String that best describes your own Objects.

println(m)实际上是调用m.toString()以获取对象的人类可读表示。它是 each 固有的Object,因此您始终可以覆盖它以使其返回最能描述您自己的对象的字符串。