当你需要输出一个对象的时候,如果不重写toString方法,则会输出:com.xuan.oop.ToStringTest@7f12f614,打印输出类名和散列码;当你想输出一个你想格式化的结果,就需要编写toString()方法。
public class ToStringTest {
int x,y;
public ToStringTest(){}
/*构造方法*/
public ToStringTest(int anX,int anY){
this.x=anX;
this.y=anY;
}
/*覆盖toString()方法*/
public String toString(){
return "ToStringTest["+x+","+y+"]";
}
/*主方法创建并输出一个对象*/
public static void main(String[] args) {
System.out.println(new ToStringTest(42,86));
}
}
另外,如果要打印出数组,可借助Arrays:
public static void main(String[] args) {
int[] lucky={1,2,3,4,5,6};
String s=Arrays.toString(lucky);
System.out.println(s);
}
如果想要打印多维数组,则使用:Arrays.deepToString()方法。