Java 奇怪的行为是修改列表
我最近写了一个方法来连接一些文本文件中的值,然后修改我想要的值。在我编写的方法中,我在下面的代码中获得了“数组索引”:Java 奇怪的行为是修改列表,java,Java,我最近写了一个方法来连接一些文本文件中的值,然后修改我想要的值。在我编写的方法中,我在下面的代码中获得了“数组索引”: String[] s = new String[] {"Value1", "Value2",...} List<List<String[]>> Temp = new ArrayList(); for (List<String[]> i : JL) { List<String[]> _Temp = new
String[] s = new String[] {"Value1", "Value2",...}
List<List<String[]>> Temp = new ArrayList();
for (List<String[]> i : JL) {
List<String[]> _Temp = new ArrayList();
for (String[] x: i) {
for (String y : s) {
if (x[0].equals(y))
_Temp.add(x);
}
}
_Temp.get(10)[0] = "Some Value"; // Index out of the array error (_Temp lenght is 12)
// _Temp.get(10) has 2 indexes
Temp.add(_Temp);
}
这是怎么发生的?修改值的两种方法完全相同
演示:
好吧
- 这两个代码段都不能确保
\u Temp ArrayList
- 替换代码段在
上工作,而失败代码段在Temp
上工作\u Temp
\u Temp
和Temp
的元素混在一起@Boann:不,我发现了,在第一个方法中,我替换了\u Temp.get(10)[0]=“Some Value”使用System.out.ptintln(_Temp.get(10)[0])
进行编码,我可以看到值。“=”操作符对列表做了一些不好的事情,比如副作用。我通过在控制台中输出列表大小来检查它
for (List<String[]> x : Temp) {
x.get(10)[0] = "Some Value";
}