有人可以向我解释该类中toString()定义的方法的概念Object吗?它是如何使用的,目的是什么?
有人可以向我解释该类中toString()定义的方法的概念Object吗?它是如何使用的,目的是什么?
Answers:
从Object.toString文档:
返回对象的字符串表示形式。通常,该
toString方法返回一个“以文本形式表示”此对象的字符串。结果应该是简洁易懂的表示形式,便于人们阅读。建议所有子类都重写此方法。
toString用于类的方法Object返回一个字符串,该字符串由对象是其实例的类的名称,符号字符“ @”以及对象的哈希码的无符号十六进制表示组成。换句话说,此方法返回的字符串等于:
getClass().getName() + '@' + Integer.toHexString(hashCode())
例:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;@13aaa14a
使用 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... 的想法
toString不是预期的,也不适合用于UI。
toStringGUI来显示对象?如果我有一个丰富的对象,并且想要在GUI中显示它,那么不,我不会为其创建额外的渲染器,也不会从该对象中提取字符串属性以在GUI中使用它,所以我将其保留简单易行,toString可以规避所有开销。如果要以更简洁的方式执行此操作,请创建一个专用于UI的包装器类,并实现其toString方法以返回包装的字符串属性。
该toString()方法返回对象的文本表示形式。一个基本的实现已经包含在其中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()+"]";
}
}
它可以有选择地在应用程序上下文中使用,但更多时候用于调试目的。例如,当您在IDE中遇到断点时,阅读有意义的内容要容易得多toString()的对象要比检查其成员得多。
对于toString()方法应该做什么没有固定的要求。按照惯例,大多数情况下它将告诉您类的名称以及相关数据成员的值。很多时候,toString()方法是在IDE中自动生成的。
依靠toString()方法的特定输出或在程序中解析它是一个坏主意。无论您做什么,都不要沿着那条路走。
toString()返回对象的字符串/文本表示形式。通常用于诊断目的,例如调试,日志记录等,toString()方法用于读取有关对象的有意义的详细信息。
当对象传递给println,print,printf,String.format(),assert或字符串串联运算符时,将自动调用它。
使用以下逻辑,类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 - Coordinates@addbf1 //concise, but not really useful to the reader
现在,如下重写Coordinates类中的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 Bond=Coordinates@addbf1, Jason Bourne=Coordinates@42e816}
很少有实现指针,
为返回的字符串中包含的所有实例字段提供访问器/获取器。例如,在“坐标”类中,
public double getX() {
return x;
}
public double getY() {
return y;
}JoString Bloch在《有效Java™,第二版》一书的第10条中全面介绍了toString()方法。
编码:
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 [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;
}
}
输出:
[史蒂夫12丹尼尔,萨钦10滕杜卡]
[史蒂夫12丹尼尔,萨钦10滕杜尔卡,尤维12巴吉]
如果您在Pojo(Student.java)类中不习惯使用toString(),则将获得类似的输出[com.steve.test.Student@6e1408, com.steve.test.Student@e53108]。为避免此类问题,我们使用toString()方法。
每当您在String上下文中访问Object(不是String)时,toString()就会在编译器的幕后被调用。
这就是为什么
Map map = new HashMap();
System.out.println("map=" + map);
起作用,并且通过在您自己的类中覆盖Object中的标准toString(),还可以使您的对象在String上下文中也很有用。
(并认为它是一个黑匣子!决不要将内容用于呈现给人类的东西)
/**
* 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();
}