更改Java列表中的引用 [英] Change the reference in a Java List

查看:96
本文介绍了更改Java列表中的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想问这个问题很愚蠢,但是

I somehow feel stupid to ask this question, BUT

为什么不能使用EnhancedForStatement 手动更改List中对对象的引用?

Why is it not possible to change the reference to an object in a List by hand using the EnhancedForStatement?

private static List<String> list = new ArrayList<String>();

public static void main(String[] args) {
    list.add("AAA");
    list.add("BBB");
    list.add("CCC");

    for(String s : list){
        if(s.equals("BBB")) s = "QQQ";
    }

    System.out.println(list);
}

将打印[AAA, BBB, CCC],因为对第二个元素的引用没有像人们期望的那样被更改.

Will print [AAA, BBB, CCC] because the reference to the second element wasn't changed, as one could expect.

但是为什么不允许我(或者List是错误的类型?)手动更改列表条目的引用?在此示例中,字符串可以是任何复杂的类型,这个问题是关于List中引用的更改.

But why am I not allowed (or is List the wrong type?) to manually change the reference of the list entry? String in this example could be any complex type, this question is about the changing of references in a List.

编辑:好的,也许很清楚为什么它能按其工作方式运行,但是我该如何完成参考更改?我不敢相信List的任何子类型都无法更改任何元素的引用.

edit: OK, maybe it is clear why it works the way it works, but how can I accomplish the reference change? I can't believe there is no way for any subtype of List to change the reference of any element.

edit2 :是否无法在使用EnhancedForStatement时更改引用?

edit2: so it is not possible to change the reference when using the EnhancedForStatement?

推荐答案

s是一个String变量,对其进行分配不会影响该列表.

s is a String variable, and assigning to it doesn't affect the list.

要更改列表,请调用list.set(1,"QQQ");,这会将新的String用作列表的第二个元素.

In order to change the list, call list.set(1,"QQQ");, which would put a new String as the second element of the list.

这篇关于更改Java列表中的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆