Java 何时使用 toString() 方法

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

when to use toString() method

javatostring

提问by

This may sound very basic... can someone please explain the use of the toString()method and when to effectively use this?

这可能听起来很基本......有人可以解释一下该toString()方法的使用以及何时有效地使用它吗?

Have done a search on google but could not find any good resource.

已经在谷歌上搜索过,但找不到任何好的资源。

采纳答案by Jeff Sternal

In most languages, toStringor the equivalent method just guarantees that an object can be represented textually.

在大多数语言中,toString或者等价的方法只是保证一个对象可以用文本表示。

This is especially useful for logging, debugging, or any other circumstance where you need to be able to render any and every object you encounter as a string.

这对于日志记录、调试或任何其他需要能够将遇到的任何对象呈现为字符串的情况特别有用。

Objects often implement custom toStringbehavior so that the method actually tells you something about the object instance. For example, a Personclass might override it to return "Last name, First name" while a Dateclass will show the date formatted according to some default setting (such as the current user interface culture).

对象通常实现自定义toString行为,因此该方法实际上会告诉您有关对象实例的一些信息。例如,一个Person类可能会覆盖它以返回“姓,名”,而一个Date类将显示根据某些默认设置(例如当前用户界面文化)格式化的日期。

回答by Oded

Assuming .NET or Java:

假设 .NET 或 Java:

In general, you should overload ToString() when you want a textual representation of your class (assuming it makes sense for your class).

通常,当您想要类的文本表示时(假设它对您的类有意义),您应该重载 ToString()。

回答by Dan

You can use toString() on an class by overriding it to provide some meaningful text representation of your object.

您可以在类上使用 toString() 通过覆盖它来提供对象的一些有意义的文本表示。

For example you may override toString() on a Person class to return the first and last name.

例如,您可以在 Person 类上覆盖 toString() 以返回名字和姓氏。

回答by rerun

To string is should be used when you have a need to change a data type to a string. For built in types like int and such there string representations are what you expect. ie

当您需要将数据类型更改为字符串时,应使用 To string。对于像 int 这样的内置类型,字符串表示就是你所期望的。IE

  int i = 5;
  string s = i.ToString(); //s now equals "5" 

Gives you the character string "5" for most complex types and all user created types you need to overload the tostring method or you will only get the name of the class. To string allows you to use the complex formating build into .net with your own objects. you can provide complex formatters like the datetime class does to give flexibility in using your own types.

为大多数复杂类型和所有用户创建的类型提供字符串“5”,您需要重载 tostring 方法,否则您将只获得类的名称。To string 允许您使用复杂的格式构建到 .net 中,并带有您自己的对象。您可以提供像 datetime 类那样的复杂格式化程序,以便灵活地使用您自己的类型。

回答by Llistes Sugra

  1. You want to display an object and don't want to check if it is null before.
  2. You want to concat Strings and not thinking about a special attribute, just provide a default one to the programmer.
  1. 您想显示一个对象并且不想检查它之前是否为空。
  2. 您想连接字符串而不考虑特殊属性,只需为程序员提供一个默认属性即可。

Thus:

因此:

out.println("You are " + user);

will display "You are null" or "You are James" if user is null or toString displays "James" for this (existent) instance.

如果用户为 null 或 toString 为这个(存在的)实例显示“James”,则将显示“You are null”或“You are James”。

回答by ponzao

There are several situations in which one would wish to override the toString method of a class (most of which are already mentioned in the existing answers), but one of the most common situations in which I have needed to explicitly call toString on an object is when using StringBuilder to construct a String.

在几种情况下,人们希望覆盖类的 toString 方法(现有答案中已经提到了其中大部分),但我需要在对象上显式调用 toString 的最常见情况之一是使用 StringBuilder 构造字符串时。

public String createString(final String str) {
  final StringBuilder sb = new StringBuilder(str);
  sb.append("foo");
  sb.append("bar");
  return sb.toString();
}

回答by Rambabu Dushetty

toString() can be used to avoid the hexadecimal address, so to overcome this problem you need to override toString() then you will get original text format of data.

toString() 可以用来避免十六进制地址,因此要解决这个问题,您需要覆盖 toString() ,然后您将获得原始文本格式的数据。

回答by rajukumarsah

When you print reference variable then following task will happen.

当您打印参考变量时,将发生以下任务。

  • if reference variable contains null then null value will be displayed.
  • if reference variable contains address of an object then toString()Method will be called by the JVM automatically.
  • 如果引用变量包含空值,则将显示空值。
  • 如果引用变量包含对象的地址,则toString()JVM 将自动调用 Method。

By default toString()of Object.classwill print:

默认情况toString()Object.class将打印:

ClassName@HexadecimalOfHashCode

类名@HexadecimalOfHashCode

You can override this method in your class to display some meaningful String. Usually toString()method is used to print contents of an object.This method is already overridden in many java built-in class like String,StringBuffer,integeretc.

您可以在类中覆盖此方法以显示一些有意义的字符串。通常toString()的方法是用来打印object.This方法的内容已经被覆盖在许多Java内置类像StringStringBufferinteger等等。

回答by Zul Qarnain

It used when we have to display the field values which we initialize through constructor and what to display without using any getter.

当我们必须显示通过构造函数初始化的字段值以及在不使用任何 getter 的情况下显示的内容时使用它。

    import Test.Date;
public class Employ {

private String firstname;
private String lastname;
private Date DOB;
private Date DOH;
public Employ(String name,String lastname,Date DOB,Date DOH)
{
    this.firstname=name;
    this.lastname=lastname;
    this.DOB=DOB;
    this.DOH=DOH;

}

    public  String toString(){

    return String.format("%s %s Birthday %s Hired %s",firstname,lastname,DOB,DOH);      
        }
public static void main (String args[])
{
    Date dob= new Date(12,3,1992);
    Date doh= new Date(10,6,2005);

    Employ em= new Employ("BOB", "Wrigh", dob,doh);

    System.out.println(em);

}

}

}