要是在toString()中使用循环,建议用下面的方法

    1. public class UsingStringBuilder {
    2. public static Random rand = new Random(47);
    3. public String toString(){
    4. StringBuilder result = new StringBuilder("[");
    5. for (int i = 0; i <10 ; i++) {
    6. result.append(rand.nextInt(100));
    7. result.append(",");
    8. }
    9. result.append("]");
    10. return result.toString();
    11. }
    12. public static void main(String[] args) {
    13. UsingStringBuilder usb = new UsingStringBuilder();
    14. System.out.println(usb);
    15. }
    16. }
    17. 输出:
    18. [58,55,93,61,61,29,68,0,22,7,]