java 中的 toString 方法的作用就是:能够使用 println 将对象直接打印出来。 使用 Arrays 的 toString 方法则可以将一个数组直接打印出来。
若是多维数组,需要用 deepToString 才能打印出数字,否则只能显示地址。
我发现,在重新定义一个对象的 toString 方法时,必须声明为 public.
举例:
public class toStringTest {
public static class Item{
double price;
String name;
public Item(double price, String name){
this.price=price;
this.name=name;
}
public String toString(){
return "price is "+price+"; name is "+name;
}
}
public static void main(String[] args) {
Item apple=new Item(1.2,"apple");
System.out.println(apple);
int a[]={1,2,3};
System.out.println(Arrays.toString(a));
int b[][]={{1,2,3},{4,5,6}};
System.out.println(Arrays.deepToString(b));
}}
显示效果:
price is 1.2; name is apple[1, 2, 3][[1, 2, 3], [4, 5, 6]]