如何在Java中使用toString方法?
有人能给我解释一下如何在Java中使用toString方法?,java,Java,有人能给我解释一下对象类中定义的toString()方法的概念吗?它是如何使用的,它的用途是什么?它可以在应用程序的上下文中选择性地使用,但更多的时候是用于调试目的。例如,当您在IDE中遇到断点时,读取对象的有意义的toString()要比检查其成员容易得多 对于toString()方法应该做什么,没有设置要求。按照惯例,它通常会告诉您类的名称和相关数据成员的值。通常,toString()方法是在IDE中自动生成的 依赖toString()方法的特定输出或在程序中对其进行解析是个坏主意。无论你做
对象类中定义的toString()
方法的概念吗?它是如何使用的,它的用途是什么?它可以在应用程序的上下文中选择性地使用,但更多的时候是用于调试目的。例如,当您在IDE中遇到断点时,读取对象的有意义的toString()
要比检查其成员容易得多
对于toString()
方法应该做什么,没有设置要求。按照惯例,它通常会告诉您类的名称和相关数据成员的值。通常,toString()
方法是在IDE中自动生成的
依赖toString()
方法的特定输出或在程序中对其进行解析是个坏主意。无论你做什么,都不要走这条路。从文档:
返回的字符串表示形式
对象通常,toString
方法返回一个
“文本表示”此对象。
结果应该是一个简洁但不复杂的过程
信息表示法,即
一个人容易阅读。它是
建议所有子类
重写此方法
类对象的toString
方法
返回由
对象所属的类的名称
是一个实例,at符号字符
`@,以及无符号十六进制
的哈希代码的表示形式
对象换句话说,这种方法
返回一个等于该值的字符串
其中:
例如:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;@13aaa14a
除了cletus回答的关于调试的问题外,每当您输出一个对象时都会使用它,比如当您使用
System.out.println(myObject);
或
toString的主要用途是生成对象的字符串表示,这意味着返回值始终是字符串。在大多数情况下,这只是对象的类和包名,但在某些情况下,如StringBuilder,您实际上会得到一个字符串文本。每当您在字符串上下文中访问对象(不是字符串)时,编译器就会在幕后调用toString()
这就是为什么
Map map = new HashMap();
System.out.println("map=" + map);
通过在您自己的类中重写标准toString()from对象,您可以使对象在字符串上下文中也很有用
(并且认为它是一个黑盒子!永远,永远不要使用内容,而不是向人展示)
< P> <代码> toStReg()/Case>方法返回一个对象的文本表示。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()+"]";
}
}
toString()
将指定的对象转换为字符串值。使用字符串。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());
}
}
}
pack1;
导入java.util.*;
班级银行{
字符串n;
字符串添加;
INTAN;
国际余额;
国际环保署署长;
公共银行(字符串n、字符串add、整数an、整数bal){
this.add=添加;
this.bal=bal;
this.an=an;
这个,n=n;
}
公共字符串toString(){
return“客户名称:”+this.n+“,”
+客户地址:“+this.add+”,“+”账号:
+此.an+”、“+”余额在A/c中:“+this.bal;
}
}
公开课演示2{
公共静态void main(字符串[]args){
列表l=新的LinkedList();
b1银行=新银行(“naseem1”,“比哈尔达邦加”,123,1000);
银行b2=新银行(“naseem2”,“比哈尔巴特纳”,1241500);
银行b3=新银行(“naseem3”,“比哈尔邦madhubani”,1251600);
银行b4=新银行(“naseem4”,“比哈尔邦萨马斯蒂普尔”,1261700);
银行b5=新银行(“naseem5”,“比哈尔邦穆扎菲尔布尔”,1271800);
l、 添加(b1);
l、 添加(b2);
l、 添加(b3);
l、 添加(b4);
l、 添加(b5);
迭代器i=l.迭代器();
while(i.hasNext()){
System.out.println(i.next());
}
}
}
。。。将此程序复制到Eclipse中,然后运行它。。。您将了解有关String的想法。正确重写toString方法可以帮助记录和调试Java。返回对象的字符串/文本表示形式。
/**
* 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();
}
toString()方法通常用于调试、记录等诊断目的,用于读取有关对象的有意义的详细信息
当对象被传递到println、print、printf、String.format()、assert或字符串连接运算符时,会自动调用它
类对象中toString()的默认实现返回一个字符串,该字符串由该对象的类名后跟@sign和该对象哈希代码的无符号十六进制表示组成,使用以下逻辑:
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);
}
}
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);
}
印刷品
Bourne's current location - Coordinates@addbf1 //concise, but not really useful to the reader
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
现在,在坐标类中重写toString(),如下所示
@Override
public String toString() {
return "(" + x + ", " + y + ")";
}
导致
Bourne's current location - (1.0, 2.0) //concise and informative
当在包含对这些对象的引用的集合上调用该方法时,重写toString()的用处就更大了。例如,以下
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);
}
}
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=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}
很少有实现指针
您几乎应该总是重写toString()方法。其中一种不需要重写的情况是,将静态实用程序方法分组的实用程序类,其方式为。不需要覆盖的情况非常直观;几乎阿尔瓦
public double getX() {
return x;
}
public double getY() {
return y;
}
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);
}
}
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;
}
}