什么输出?

时间:2013-02-18 17:52:41

标签: java pass-by-reference

传递引用让我有点头疼,所以我想看看社区其他人会发现这个问题有多么混乱。如果您认为这是一个愚蠢的问题,请随时说出来。

您认为以下程序的输出是什么?

class Demo {
    public static void main(String[] args) {
        ArrayList<Container> list = new ArrayList<Container>();
        Container c1 = new Container();
        Container c2 = new Container();
        c1.setSt("c1");
        c2.setSt("c2");
        list.add(c1);
        list.add(c2);

        Container c3 = new Container();
        c3.setSt("c3");
        modify(list, c3);

        for (Container st : list) {
            System.out.println(st.getSt());
        }
        System.out.println("c3.st: " + c3.getSt());
    }

    private static void modify(ArrayList<Container> list, Container container) {
        list.get(1).setSt("modified");
        container.setSt("modified c3");
        container = new Container();
        container.setSt("new container");
    }
}

class Container {
    private String st;

    public String getSt() {
        return st;
    }

    public void setSt(String st) {
        this.st = st;
    }
}

1 个答案:

答案 0 :(得分:0)

c1
modified
c3.st: modified c3

我赢了什么?