我有一个二维对象列表。我正在尝试访问一个列表并将其替换为其自身的子列表。我在下面做了一个简单的例子,我想用 dList.get(0).subList(1,3) 替换 dList.get(0) 。我使用引用变量,它更新原始列表中的值,但子列表没有更新。我对此有点陌生,非常感谢任何以示例、解释和指导文档形式提供的帮助。
List<List<Double>> dList = new ArrayList<List<Double>>();
/**
* Initialize, the 2D List with some values
*/
protected void init() {
List<Double> d = new ArrayList<Double>();
d.add(1.0);
d.add(2.0);
d.add(3.0);
d.add(4.0);
d.add(5.0);
dList.add(d);
}
/**
* Check if the subList update works.
*/
protected void check() {
List<Double> tmp = dList.get(0); //get the reference into a temporary variable
tmp = tmp.subList(1, 3); //get the sublist, in the end the original list dList.get(0) should be this.
tmp.set(0, 4.5); //reference works, the dList.get(0) values get updated
for (int i = 0; i < tmp.size(); i++) {
System.out.println(tmp.get(i));
}
System.out.println("....Original 2D List Values....");
for (int i = 0; i < dList.get(0).size(); i++) {
System.out.println(dList.get(0).get(i)); // still has all the elements, and not the sublist
}
System.out.println("Result" + dList.get(0).size());
}
最佳答案
tmp.subList()
返回一个与 dList
的第一个元素不同的新 List 实例。这就是原始列表没有改变的原因。
您需要设置 dList
的第一个元素来引用您创建的子列表:
List<Double> tmp = dList.get(0);
tmp = tmp.subList(1, 3);
tmp.set(0, 4.5);
dList.set (0, tmp);
关于java - 2D 列表中的子列表,引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30783260/