如何在 Java 中使用 toString 方法?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3615721/
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-08-14 02:42:26  来源:igfitidea点击:

How to use the toString method in Java?

java

提问by David Brown

Can anybody explain to me the concept of the toString()method, defined in the Objectclass? How is it used, and what is its purpose?

任何人都可以向我解释类中toString()定义的方法的概念Object吗?它是如何使用的,它的目的是什么?

采纳答案by Sean Patrick Floyd

From the Object.toStringdocs:

Object.toString文档:

Returns a string representation of the object. In general, the toStringmethod 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.

The toStringmethod for class Objectreturns 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:

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

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

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

Example:

例子:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());

output:- mystr.toString: [Ljava.lang.String;@13aaa14a

回答by cletus

It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString()of objects than it is to inspect their members.

它可以有选择地在应用程序的上下文中使用,但更常用于调试目的。例如,当您在 IDE 中遇到断点时,读取有意义toString()的对象要比检查其成员容易得多。

There is no set requirement for what a toString()method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString()methods are auto-generated in IDEs.

对于toString()方法应该做什么没有固定的要求。按照惯例,它通常会告诉您类的名称和相关数据成员的值。通常,toString()方法是在 IDE 中自动生成的。

Relying on particular output from a toString()method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.

依赖toString()方法的特定输出或在程序中解析它是一个坏主意。不管你做什么,都不要走那条路。

回答by Frank

Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use

除了 cletus 在调试方面的回答之外,每当您输出对象时都会使用它,例如当您使用

 System.out.println(myObject);

or

或者

System.out.println("text " + myObject);

回答by heb

The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.

toString 的主要目的是生成一个对象的字符串表示,意味着返回值始终是一个字符串。在大多数情况下,这只是对象的类和包名称,但在某些情况下,例如 StringBuilder,您实际上会得到一个字符串文本。

回答by Thorbj?rn Ravn Andersen

Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.

每当您在字符串上下文中访问对象(不是字符串)时,编译器都会在幕后调用 toString()。

This is why

这就是为什么

Map map = new HashMap();
System.out.println("map=" + map);

works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.

有效,并且通过在您自己的类中从 Object 覆盖标准 toString(),您也可以使您的对象在 String 上下文中有用。

(and consider it a black box! Never, ever use the contents for anything else than presenting to a human)

(并认为它是一个黑匣子!永远不要将内容用于展示给人类以外的任何其他用途)

回答by Andreas Dolk

The toString()method returns a textualrepresentation of an object. A basic implementation is already included in java.lang.Objectand so because all objects inherit from java.lang.Objectit is guaranteed that every object in Java has this method.

toString()方法返回对象的文本表示。一个基本的实现已经包含在java.lang.Objectand 所以因为从java.lang.Object它继承的所有对象保证 Java 中的每个对象都有这个方法。

Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString()method. So use a meaningful implementation but use it for technicalpurposes. The application logic should use getters:

覆盖该方法总是一个好主意,尤其是在调试时,因为调试器通常根据toString()方法的结果显示对象。因此,请使用有意义的实现,但将其用于技术目的。应用程序逻辑应该使用 getter:

public class Contact {
  private String firstName;
  private String lastName;
  public Contact (String firstName, String lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }
  public String getFirstName() {return firstName;}
  public String getLastName() {return lastName;}

  public String getContact() {
    return firstName + " " + lastName;
  }

  @Override
  public String toString() {
    return "["+getContact()+"]";
  }
}

回答by ankit

the toString()converts the specified object to a string value.

toString()指定对象为字符串值的转换。

回答by Naseem Afzal

Use of the String.toString:

的使用String.toString

Whenever you require to explore the constructor called value in the Stringform, you can simply use String.toString... for an example...

每当您需要探索String表单中名为 value 的构造函数时,您可以简单地使用String.toString... 作为示例...

package pack1;

import java.util.*;

class Bank {

    String n;
    String add;
    int an;
    int bal;
    int dep;

    public Bank(String n, String add, int an, int bal) {

        this.add = add;
        this.bal = bal;
        this.an = an;
        this.n = n;

    }

    public String toString() {
        return "Name of the customer.:" + this.n + ",, "
                + "Address of the customer.:" + this.add + ",, " + "A/c no..:"
                + this.an + ",, " + "Balance in A/c..:" + this.bal;
    }
}

public class Demo2 {

    public static void main(String[] args) {

        List<Bank> l = new LinkedList<Bank>();

        Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
        Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
        Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
        Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
        Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
        l.add(b1);
        l.add(b2);
        l.add(b3);
        l.add(b4);
        l.add(b5);
        Iterator<Bank> i = l.iterator();
        while (i.hasNext()) {
            System.out.println(i.next());
        }
    }

}

... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...

... 将此程序复制到您的 Eclipse 中,然后运行它...您将了解String.toString...

回答by USM167

Correctly overridden toString method can help in logging and debugging of Java.

正确覆盖 toString 方法可以帮助记录和调试 Java。

回答by redestructa

/**
 * This toString-Method works for every Class, where you want to display all the fields and its values
 */
public String toString() {

    StringBuffer sb = new StringBuffer();

    Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones

    for (Field field : fields){

        try {

            field.setAccessible(true);
            String key=field.getName();
            String value;

            try{
                value = (String) field.get(this);
            } catch (ClassCastException e){
                value="";
            }

            sb.append(key).append(": ").append(value).append("\n");

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    return sb.toString();
}