如何在Java中使用toString方法?


118

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



这也是一个快速的技巧/快速实现:@Override public String toString(){return org.apache.commons.lang3.builder.ToStringBuilder.reflectionToString(this); }
granadaCoder '19

Answers:


81

Object.toString文档:

返回对象的字符串表示形式。通常,该toString 方法返回一个“以文本形式表示”此对象的字符串。结果应该是简洁易懂的表示形式,便于人们阅读。建议所有子类都重写此方法。

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

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

例:

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

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

1
主要目的是在子类中重写它。我认为@stephen和Andreas_D的答案比公认的答案要好。
Sree Rama

39

使用 String.toString

每当您需要探索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());
        }
    }

}

...将此程序复制到Eclipse中,然后运行它...您将获得有关String.toString... 的想法


5
希望您知道这toString不是预期的,也不适合用于UI。
Powerslave

然后@Powerslave解释为什么所有的Swing组件都使用toStringGUI来显示对象?如果我有一个丰富的对象,并且想要在GUI中显示它,那么不,我不会为其创建额外的渲染器,也不会从该对象中提取字符串属性以在GUI中使用它,所以我将其保留简单易行,toString可以规避所有开销。如果要以更简洁的方式执行此操作,请创建一个专用于UI的包装器类,并实现其toString方法以返回包装的字符串属性。
2015年

1
@Timmos如果您的朋友跳下桥,您会跟随吗?仅仅因为Swing开发人员使用(读取;滥用)toString函数并不意味着您也应该这样做。
Toby Caulk

2
鉴于您继续使用默认的Swing API,这是迄今为止完成工作的最简单方法。如果要自定义渲染,可以在组件上安装自定义渲染器。如果您只想显示一个由String表示的对象,则与自定义渲染器相比,实现toString()更加容易,自定义渲染器完全可以做到这一点。我认为您与跳桥的比较很奇怪。
Timmos

35

toString()方法返回对象的文本表示形式。一个基本的实现已经包含在其中java.lang.Object,因此,因为所有对象都继承自java.lang.Object该实现,因此可以确保Java中的每个对象都具有此方法。

重写该方法始终是一个好主意,尤其是在调试时,因为调试器通常根据该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()+"]";
  }
}

14

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

对于toString()方法应该做什么没有固定的要求。按照惯例,大多数情况下它将告诉您类的名称以及相关数据成员的值。很多时候,toString()方法是在IDE中自动生成的。

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


2
您能否详细说明您的最后声明?
Jean-Philippe Caruana

13

toString()返回对象的字符串/文本表示形式。通常用于诊断目的,例如调试,日志记录等,toString()方法用于读取有关对象的有意义的详细信息。

当对象传递给println,print,printf,String.format(),assert或字符串串联运算符时,将自动调用它。

使用以下逻辑,类Object的toString()的默认实现返回一个字符串,该字符串由该对象的类名称,后跟@符号和该对象的哈希码的无符号十六进制表示组成,

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

例如,以下

public final class Coordinates {

    private final double x;
    private final double y;

    public Coordinates(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public static void main(String[] args) {
        Coordinates coordinates = new Coordinates(1, 2);
        System.out.println("Bourne's current location - " + coordinates);
    }
}

版画

Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader

现在,如下重写Coordinates类中的toString(),

@Override
public String toString() {
    return "(" + x + ", " + y + ")";
}

结果是

Bourne's current location - (1.0, 2.0) //concise and informative

当在包含对这些对象的引用的集合上调用该方法时,重写toString()的作用变得更大。例如,以下

public static void main(String[] args) {
    Coordinates bourneLocation = new Coordinates(90, 0);
    Coordinates bondLocation = new Coordinates(45, 90);
    Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
    locations.put("Jason Bourne", bourneLocation);
    locations.put("James Bond", bondLocation);
    System.out.println(locations);
}

版画

{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}

而不是这个

{James Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}

很少有实现指针,

  1. 您几乎应该始终重写toString()方法。不需要重写的一种情况是以java.util.Math的方式对静态实用程序方法进行分组的实用程序类。不需要覆盖的情况非常直观。几乎总是你会知道的。
  2. 返回的字符串应简明扼要,内容丰富,理想情况下是不言而喻的。
  3. 至少,用于在两个不同对象之间建立等效性的字段,即equals()中使用的字段方法实现中应该由toString()方法吐出。
  4. 为返回的字符串中包含的所有实例字段提供访问器/获取器。例如,在“坐标”类中,

    public double getX() {
        return x;
    }
    public double getY() {
        return y;
    }

JoString Bloch在《有效Java™,第二版》一书的第10条中全面介绍了toString()方法。


6

编码:

public class Test {

    public static void main(String args[]) {

        ArrayList<Student> a = new ArrayList<Student>();
        a.add(new Student("Steve", 12, "Daniel"));
        a.add(new Student("Sachin", 10, "Tendulkar"));

        System.out.println(a);

        display(a);

    }

    static void display(ArrayList<Student> stu) {

        stu.add(new Student("Yuvi", 12, "Bhajji"));

        System.out.println(stu);

    }

}

Student.java:

public class Student {

    public String name;

    public int id;

    public String email;

    Student() {

    }

    Student(String name, int id, String email) {

        this.name = name;
        this.id = id;
        this.email = email;

    }

     public String toString(){           //using these toString to avoid the output like this [com.steve.test.Student@6e1408, com.steve.test.Student@e53108]
          return name+" "+id+" "+email;     
         }  


    public String getName(){

        return name;
    }

    public void setName(String name){

        this.name=name;
    }

    public int getId(){

        return id;
    }

    public void setId(int id){

        this.id=id;
    }

    public String getEmail(){

        return email;

    }

    public void setEmail(String email){

        this.email=email;
    }
}

输出:

[史蒂夫12丹尼尔,萨钦10滕杜卡]

[史蒂夫12丹尼尔,萨钦10滕杜尔卡,尤维12巴吉]

如果您在Pojo(Student.java)类中不习惯使用toString(),则将获得类似的输出[com.steve.test.Student@6e1408, com.steve.test.Student@e53108]。为避免此类问题,我们使用toString()方法。


4

每当您在String上下文中访问Object(不是String)时,toString()就会在编译器的幕后被调用。

这就是为什么

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

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

(并认为它是一个黑匣子!决不要将内容用于呈现给人类的东西)


3

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


2

除了cletus关于调试的回答之外,每当您输出对象时(例如当您使用

 System.out.println(myObject);

要么

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

1

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


0
/**
 * 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();
}

0

如果您先学习Python,然后再学习Java。我认为它与__str__()Python中的方法具有相同的作用,它是一种神奇的方法,就像__dict__()和一样,__init__()但是要引用表示对象的字符串。


-1

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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.