2010-09-01 77 views
92

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

+5

重复的http://stackoverflow.com/questions/2329168/when-to-use-tostring-method和http://stackoverflow.com/questions/2887640/what-is-the-use-of-tostring -in-java – pavanlimo 2010-09-01 07:11:40

回答

70

Object.toString()文档:

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

Object类的toString方法 返回一个由 名称的类的,其的目的 是一个实例,该符号字符 '@”的字符串,和散列的无符号十六进制 表示代码为 对象。换句话说,这种方法 返回一个字符串等于值 :

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

例子:

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

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

主要目的是在子类中覆盖它。我认为@stephen和Andreas_D的答案比接受的答案要好。 – 2017-06-12 16:01:54

12

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

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

依靠toString()方法的特定输出或在程序中对其进行解析是一个坏主意。无论你做什么,都不要走这条路。

+0

能否详细说明你最后的陈述? – 2013-09-20 08:58:06

2

除了什么克莱图斯至于调试回答,它是用来当你输出物体,如当您使用时

System.out.println(myObject); 

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

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

4

无论何时在String上下文中访问对象(不是字符串)时,编译器会在封面下调用toString()。

这就是为什么

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

作品,并通过覆盖标准的toString()从对象在自己的类,你可以让你的对象字符串环境太有用了。

(并认为这是一个黑盒子!永远不要使用该内容的任何东西比呈现给其他人)

25

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

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

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()+"]"; 
    } 
} 
0

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

34

使用String的toString: 每当你需要探索堪称字符串形式值的构造方法,你可以简单地使用字符串的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,并运行它......你会得到关于字符串的ToString想法...

+0

非常感谢你... – 2012-10-25 12:51:22

+3

我希望你知道'toString'不是用于UI的目的,也不适合用于UI目的。 – Powerslave 2014-10-31 10:12:48

+0

@Powerslave然后解释为什么所有Swing组件都使用'toString'在GUI中显示对象?如果我有一个丰富的对象,我想在GUI中显示它,那么不,我不会为它创建一个额外的渲染器,也不会从对象中提取字符串属性以在GUI中使用它,我保留它简单并实现'toString'能够规避所有的开销。如果你想以更干净的方式做到这一点,创建一个专用于UI目的的包装类,并实现其'toString'方法来返回wrappee的字符串属性。 – Timmos 2015-02-18 09:36:46

3

正确重写的ToString方法可以在记录和Java的调试帮助。

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(); 
} 
8

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

当对象被传递给println,打印,printf的,的String.format()这是自动调用,断言或串并置运算符。

类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 - [email protected] //concise, but not really useful to the reader 
现在

,覆盖在如下的坐标类的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 [email protected], Jason [email protected]} 

很少执行的指针,

  1. 你应该总是重写ToString( ) 方法。其中不需要覆盖的情况之一是以java.util.Math的方式对静态实用程序方法进行分组的实用程序类。不需要覆盖的情况非常直观;几乎总是你会知道的。
  2. 返回的字符串应该简洁明了,最好不言自明。
  3. 至少,用于确定两个不同对象之间等价的字段,即方法实现中使用的字段应该由toString()方法吐出。
  4. 为返回的字符串中包含的所有实例字段提供访问器/获取器。例如,在坐标类,

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

的toString()方法的全面覆盖是在书中,有效的Java™,第二版,由乔希布洛赫的第10项。

4

编码:

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 [[email protected], [email protected]08] 
      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,Yuvi 12 Bhajji]

如果你没有在POJO的(Student.java)类使用的toString(),你会得到像[[email protected], [email protected]]输出。为了避免这些类型的问题我们正在使用toString()方法。

0

如果您先学习Python,然后再学Java。我认为它在Python中起着与__str__()方法相同的作用,它是magic method类似于__dict__()__init__(),但是指的是代表对象的字符串。