public String toString()的方法应该在什么时候使用

解决方案 »

  1.   

    额,这话说得有点太模糊了,想什么时候用就什么时候用咯。一般model类重写toString方法
      

  2.   

    从方法名上大概也看得到出来,“转换成字符串”
    但,转换的对象必须是非null的。
      

  3.   

    个人理解是:toString() 是Object类的方法,一般类都会重写这个方法,像String就是,如果不重写的话,就是返回getClass().getName() + '@' + Integer.toHexString(hashCode())。
      

  4.   

    应该是在对象需要转化为字符串的时候用的,分为隐式调用和显式调用两种吧。
    显式的就是在写代码的时候就手动地调用toString方法,将他转化为字符串。
    隐式的就是在对象和字符串进行运算或者是将对象作为参数调用print、println方法的时候,会自动调用对象的toString方法。
    比如:
    public class TestString {
    private void exchangeToString(Object str) {
    String temp = "你也好:"+str;
    System.out.println(temp);
    }
    public static void main(String[] args) {
    StringExample stringExample = new StringExample(); System.out.println(stringExample);
    System.out.println(stringExample.toString());
    System.out.println("你好:" + stringExample);
    System.out.println("你好:" + stringExample.toString());
    TestString test=new TestString();
    test.exchangeToString(stringExample);
    }
    }
    class StringExample {
    @Override
    public String toString() {
    // TODO Auto-generated method stub
    return "hello";
    }
    }
    输出为:
    hello
    hello
    你好:hello
    你好:hello
    你也好:hello
      

  5.   

    需要把非字符串类型数据转换成string字型的时候。
      

  6.   

     大部分就是在System.out.printf(对象名 );自动调用 可以查查 该对象有没有重写 Object 的tostring 没的话找父类 直到Object(查API)
      

  7.   

     大部分就是在System.out.printf(对象名 );自动调用 可以查查 该对象有没有重写 Object 的tostring 没的话找父类 直到Object(查API)
      

  8.   


    大部分 System.out.printf(对象名);
      

  9.   

    重写toString()方法,可以拿到你想要的信息。
      

  10.   

    还是先去读一下java API文档下Object 类下的toString()方法的源代码