ALSTRA
ALSTRA

Reputation: 661

Java - LinkedList is initialized incorrectly

I want to implement a "back" button and for that, before I enter any function I copy the data from the main list in my temporary list. When the user clicks on the "back" button I call the tempList instead of the mainList.

But although I initialized the tempList(just once) with the old value of the mainList, after the function the tempList has the new values of the mainList....

Code:

     ObservableList<List<String>> fnlData;

     List<List<String>> fnlDataTMP;
     .
     .

private void cnvrtColumn() {

        fnlDataTMP = fnlData;

        delWV();//if the mainList(fnlData) has a change in any of this functions, the tmpList also updates the values
        delWM();
        addVN();
        addWV();
        addWM();
        dateFormat();
        changeChar();

        finalTable.getSelectionModel().clearSelection();
        finalTable.getItems().clear();
        finalTable.getColumns().clear();
        createColumns();
        finalTable.getItems().addAll(fnlData);
}

Upvotes: 1

Views: 108

Answers (3)

Astrogat
Astrogat

Reputation: 1625

When you do List listA = listB you are just telling listA and listB to point at the same list. If you want listA to be a list with the same values, but without it being the actual same values you must manually copy them.

Since the Lists are mutable you can't just clone the outer list, you must go through it and clone each of the inner lists.

So:

List<List<String>> newList = new ArrayList<List<String>>();
for(List<String> ls : outerList) {
    newList.add(oldArrayList.clone();
}

This will give you a list of cloned lists, and you can freely change all the lists in newList without it affecting anything in the oldList. Since the innerLists contains Strings (and Strings can't be changed after creation) you don't have to worry about just cloning the innerLists.

Upvotes: 2

nutfox
nutfox

Reputation: 484

You are just adding a reference to the same list.

If you truly want to copy the lists do it this way:

fnlDataTMP = new ArrayList<List<String>>(fnlData);

Assuming that the lists inside the fnlData list are manipulated you would have to do it like this to create a true copy:

fnlDataTMP = new ArrayList<List<String>>();
for (List<String> sublist : fnlData) {
    fnlDataTMP.add(new ArrayList<String>(sublist));
}

Upvotes: 1

Anto
Anto

Reputation: 4305

Just replace it with:

ObservableList<List<String>> fnlData = XCollections.observableArrayList();

And then try:

private void cnvrtColumn() {

    fnlDataTMP = new ArrayList<List<String>>(fnlData);
....

Upvotes: 1

Related Questions