Java toString method is a very useful method and even though you may not know it, I am sure you have used it a lot in your programs.
Java toString方法是一個非常有用的方法,即使您可能不知道它,我也可以肯定您在程序中使用了很多方法。
Java空指針。
System.out.println(object);
for learning and debugging purposes? I have used that a lot in my early days and still use it to debug my code (pre production). If you look at it closely, System.out
is instance of PrintStream
and it’s toString
method is implemented like below.
首先,讓我們確定為什么我之前說過即使您可能不知道toString方法,也是如此。 您是否同意使用System.out.println(object);
用于學習和調試目的? 我在早期使用了很多東西,但仍然使用它來調試我的代碼(生產前)。 如果仔細觀察, System.out
是PrintStream
實例,并且它的toString
方法實現如下。
public void println(Object x) {String s = String.valueOf(x);synchronized (this) {print(s);newLine();}
}
And String.valueOf()
implementation is like this:
java contains方法。 而且String.valueOf()
實現是這樣的:
public static String valueOf(Object obj) {return (obj == null) ? "null" : obj.toString();
}
So ultimately println()
and print()
functions are calling objects’ toString()
method to get the string representation and then print it. So below two statements will produce same result.
因此最終, println()
和print()
函數調用對象的toString()
方法來獲取字符串表示形式,然后進行打印。 因此,以下兩個語句將產生相同的結果。
System.out.println(object.toString());System.out.println(object);
java中類方法?Now that we agree that it’s being used a lot, let’s start to explore toString method in more detail.
現在我們同意它已經被大量使用了,讓我們開始更詳細地研究toString方法。
Let’s look at a simple program where we will create a java object and call it’s toString method.
Java tostring、 讓我們看一個簡單的程序,在該程序中我們將創建一個Java對象并將其稱為toString方法。
package com.journaldev.string;public class JavaToString {public static void main(String[] args) {Data d = new Data(10, "Java");System.out.println(d);}
}class Data {private int id;private String name;Data(int a, String b) {this.id = a;this.name = b;}
}
When I run and compile this program, I get output as com.journaldev.string.Data@7a46a697
.
運行并編譯該程序時,輸出為com.journaldev.string.Data@7a46a697
。
java compareto,Now two questions arise – first is where is toString() method implemented because I don’t see it in Data class? Second is what is this output that has hardly any meaningful information.
現在出現兩個問題–首先是toString()方法在哪里實現,因為我在Data類中看不到它? 其次是幾乎沒有任何有意義的信息的輸出。
We know that java supports inheritance and Object
is at the top level of this hierarchy, that is where toString
method is implemented. If you look at Object class toString implementation, it’s like this:
我們知道Java支持繼承,并且Object
在此層次結構的頂層,即toString
方法的實現位置。 如果查看Object類的toString實現,則如下所示:
public String toString() {return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
Now it’s clear why the output is having class name with @ and then some hexadecimal number.
現在很清楚為什么輸出的類名帶有@,然后是一個十六進制數。
Let’s now look at the Object toString() method javadoc and see what it says.
現在讓我們看一下Object toString()方法javadoc,看看它說了什么。
toString
method returns a string representation of the object. Java toString
方法返回對象的字符串表示形式。 Based on above recommendation, we should almost always override toString() method to return useful information about the object. So let’s change our Data class implementation and override it’s toString method.
基于以上建議,我們幾乎應該始終重寫toString()方法以返回有關該對象的有用信息。 因此,讓我們更改Data類的實現,并覆蓋它的toString方法。
package com.journaldev.string;public class JavaToString {public static void main(String[] args) {Data d = new Data(10, "Java");System.out.println(d);}
}class Data {private int id;private String name;Data(int a, String b) {this.id = a;this.name = b;}public int getId() {return id;}public String getName() {return name;}/*** Returns JSON string with id and name* Implementation can change in future, not to rely to convert object to JSON*/@Overridepublic String toString() {return "{\"id\":"+id+", \"name\":\""+name+"\"}";}
}
Now when you will run above program, output will be {"id":10, "name":"Java"}
. Now this makes more sense to anybody looking at the output.
現在,當您運行上述程序時,輸出將為{"id":10, "name":"Java"}
。 現在,這對于查看輸出的任何人都更有意義。
Let’s see some important points you should consider while overriding toString() method.
讓我們看看重寫toString()方法時應考慮的一些重要點。
List<Data> list = new ArrayList<>();
list.add(new Data(10, "Java")); list.add(new Data(20, "Python"));
System.out.println(list);
Which output you would prefer?
Without toString() implementation:
With toString() implementation:
[{"id":10, "name":"Java"}, {"id":20, "name":"Python"}]
始終最好提供toString()方法的實現,即使您可能認為它不是必需的。 考慮下面的代碼,其中有人在打印數據對象列表。 您需要哪種輸出?
沒有toString()實現 :
[com.journaldev.string.Data@7a46a697, com.journaldev.string.Data@5f205aa]
使用toString()實現 :
That’s all for brief roundup on java toString() method.
這就是對java toString()方法的簡短總結。
Reference: API Doc
參考: API文檔
翻譯自: https://www.journaldev.com/18578/java-tostring-method
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态