0

I ve stuck with the following prob. Ignore the most code, my issue is: I have a different list x every iteration and I want to parse it in the 2DarrayList conVert so I use the conVert.add(x); but my problem is on x.clear();. When I print conVert before clear conVert is ok but when i print it after clear besides x also and conVert is cleared. What can I do for this? Thanks in advance

         List<Integer> x =  new ArrayList<Integer>();
       // List<Integer> x1 =  new ArrayList<Integer>();
        List<Integer> valenceList =  new ArrayList<Integer>();
        List<List<Integer>> conVert = new ArrayList<List<Integer>>();


       for (int q = 1; q <= 4; q++) {


            for (int i = 0; i < Faces.length; i++) {

                for (int j = 0; j < 2; j++) {

                    if (Faces[i][j] == q) {

                        x.add(Faces[i][0]);
                        x.add(Faces[i][1]);
                        x.add(Faces[i][2]);

                   }
                }
            }
             removeDuplicateWithOrder((ArrayList) x);
             valenceList.add(x.size() -1);
             //x1 = x;
             conVert.add(x);
             System.out.println(conVert);
             x.clear();
              //System.out.println(conVert);
        }

2 Answers 2

1

Your addition of x to conVert is going to follow any changes to x since it's just putting a reference in the list. You could copy it like this instead:

conVert.add(new ArrayList<Integer>(x));

Alternatively you could just move the construction of x inside your first for loop and skip the clear.

Sign up to request clarification or add additional context in comments.

3 Comments

Right on. You could save a few characters with conVert.add(x.clone());, although this would mean keeping x typed as an ArrayList.
@Daniel: you'd need to cast it too, i.e. conVert.add((ArrayList) x.clone());. I'd argue that moving the construction of x into the first loop and removing the clear would save the most characters :)
Nonsense, you can just do l.getClass().getMethod("clone").invoke(l); :-)
0

If I understand you correctly, you are seeing that the contents of conVert are being cleared as well as x. This is because list.add is not a deep copy it only puts the reference to the original. What you could do is clone x and add that -

List<Integer> tempX = new List<Integer>();
tempX.addAll(x);
conVert.add(tempX);
x.clear();

That should work.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.