有人能给我解释一下Object
类中定义的toString()
方法的概念吗?它是如何使用的,它的用途是什么?
发布于 2012-10-25 20:41:49
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
的想法……
发布于 2010-09-01 15:10:22
它可以在应用程序的上下文中有选择地使用,但更多的是用于调试目的。例如,当您在集成开发环境中遇到断点时,读取对象的有意义的toString()
要比检查它们的成员容易得多。
对于toString()
方法应该做什么,没有设定的要求。按照惯例,它通常会告诉您类的名称和相关数据成员的值。通常,toString()
方法是在IDE中自动生成的。
依赖于toString()
方法的特定输出或在程序中解析它不是一个好主意。不管你做什么,都不要走那条路。
发布于 2010-09-01 15:19:40
无论何时访问字符串上下文中的对象(不是字符串),编译器都会在幕后调用toString()。
这就是为什么
Map map = new HashMap();
System.out.println("map=" + map);
工作,并且通过在您自己的类中覆盖来自Object的标准toString(),您也可以使您的对象在字符串上下文中有用。
(就当它是黑盒吧!除了向人类展示之外,永远不要将内容用于任何其他用途)
https://stackoverflow.com/questions/3615721
复制相似问题