Sublists in a 2D List, Referencing

204 views Asked by At

I have a 2D List of objects. I'm trying to access a list and replace it with a sublist of itself. I made up a simple example below, I want to replace dList.get(0) with dList.get(0).subList(1,3). I use a reference variable, which updates the values in the original list, but the subList is not getting updated. I`m a bit new to this, any help in the form of examples, explanations and directing me documentation is appreciated.

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

There are 1 answers

0
Eran On BEST ANSWER

tmp.subList() returns a new List instance that is different from the first element of dList. That's why the original List was unchanged.

You need to set the first element of dList to refer to the sub-list you created :

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