二维列表中的子列表,引用

Sublists in a 2D List, Referencing

我有一个二维对象列表。我正在尝试访问一个列表并将其替换为它自己的子列表。我在下面做了一个简单的例子,我想用 dList.get(0).subList(1,3) 替换 dList.get(0)。我使用了一个引用变量,它更新了原始列表中的值,但 subList 没有得到更新。我对此有点陌生,感谢任何以示例、解释和指导文档形式提供的帮助。

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() returns 与 dList 的第一个元素不同的新 List 实例。这就是为什么原始列表没有改变的原因。

您需要设置 dList 的第一个元素来引用您创建的子列表:

List<Double> tmp = dList.get(0); 
tmp = tmp.subList(1, 3);    
tmp.set(0, 4.5); 
dList.set (0, tmp);