1

I have a problem with Java: I have a list of integer that I want to put into a specific column and line of an array. For example, in column 1 I want to put [1,2,3] and column 2 [8]...

I tried something - I wanted to put the list into the array and then clear the list to put new values and put in another location of my array etc...

I created an array (RANG) of list and my list (ELEMENTS):

    List[] rang=new List[nbSommets];
    List<Integer> elements= new ArrayList<>(nbSommets);

I added some numbers and I put into the array ALL my list

rang[???]=elements;

Then, I clear the list to put new values

elements.clear();

But when I clear the list, this clear the list into my array too...

How can I do it ?

Thank you !

1
  • 2
    You have an array of (raw, cause generic arrays) lists. They’re just references. There’s two levels of weird going on here... Commented Apr 15, 2020 at 17:20

3 Answers 3

3

When you do rang[???] = elements; you are only assigning a reference to the array elements to rang[???], you are no copying all the values in a new array.

What you have to do is, instead of clearing the elements array, create a new array (new ArrayList<>()) every time.

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

Comments

1

Replace

elements.clear();

with

elements = new ArrayList<>(nbSommets);

Why elements.clear() clears the original ArrayList object

Because elements is still pointing to the original ArrayList object no matter whether you add it to an array, some other collection or object.

Why elements = new ArrayList<>(nbSommets) will work?

Because it will disconnect the reference to the original ArrayList object and point elements to a new ArrayList.

Comments

0

The problem is that if you create a List elements = new ArrayList(), you create a new object. If you put the list inside your array by rang[???] = elements, now your array contains reference to the List you have created. So your elements variable is pointing to the same object as as rang[???]. You can put it to array by rang[???] = new ArrayList(elements) and you will get a new List, and when you clear elements, the List in array will remain untouched.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.