2010-09-01 113 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__(),但是指的是代表對象的字符串。