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

时间:2015-06-11 14:10:29

标签: java reference sublist

我有一个2D对象列表。我正在尝试访问列表并将其替换为自己的子列表。我在下面编写了一个简单的例子,我想用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());
}

1 个答案:

答案 0 :(得分:1)

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);
相关问题