java底层基础问题,对象底层循环。


public class Snake implements Cloneable{
    private Snake next;
    private char c;

    public Snake(int i,char x) {
        c = x;
        if(--i > 0){
            next = new Snake(i,(char)(x+1));
        }
    }

    void increment(){
        c ++;
        if(next != null){
            next.increment();
        }
    }

    public String toString(){
        String s = ":" +c;
        if(next != null){
            s+= next.toString();

        }
        return s;
    }

    public Object clone(){
        Object o = null;
        try{
            o = super.clone();
        }catch(Exception e){

        }
        return o;
    }

    public static void main(String[] agrs){
        Snake s = new Snake(5,'a');
        System.out.println("s = "+ s.toString());
    }
}

以上程序运行结果为 s = :a:b:c:d:e

本人想知道为什么 重复给一个next赋值,可以有5个对象,还有toString输出的时候

为什么是一个 字符串 而不是单个字符 比如 :a,因为我从他这里没看出任何循环。

你的toString()实现就是迭代的。所以把所有的next连接起来

这个构造函数会构造,会创建i个对象,即,除了当前对象以外,【Snake next;】,的next下面会有4个

  public Snake(int i,char x) {
        c = x;
        if(--i > 0){
            next = new Snake(i,(char)(x+1));
        }
    }

这个toString,会迭代的输出,当前对象的【:c】,,,以及的next下面会有4个,的【:c】

  public String toString(){
        String s = ":" +c;
        if(next != null){
            s+= next.toString();

        }
        return s;
    }

为什么是一个 字符串, 【public String toString()】这个返回类型是一个字符串
【 s+= next.toString();】在这里会吧返回的字符串,组装成一个字符串,,最终返回
【return s;】