java - 2D 列表中的子列表,引用

标签 java reference sublist

我有一个二维对象列表。我正在尝试访问一个列表并将其替换为其自身的子列表。我在下面做了一个简单的例子,我想用 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/

相关文章:

java - 如何在没有服务器的情况下在多个设备中的同一个应用程序之间共享数据库

c++ - 使用模板将数组作为引用作为参数传递

python - 从python中的特定索引值排序列表

java - 如何更改 ExecutorService 中的线程名称?

java - 对话 fragment 中未调用 onRequestPermissionsResult

vba - 使用 VBA 代码(宏)连接引用(工具>引用)

algorithm - 包含元素 N 且总数 > MIN 的最短子列表

Python - 将部分子列表的元素转换为 int

java - 从 java 使用 OData 服务

java - 集合分配、浅复制、惰性复制和深复制的区别和最佳方法