Put a list into an array in JAVA - java

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 !

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.

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.

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.

Related

Remove Object from Clone of Array of ArrayList

My question is very basic but I am still not able to figure out how to do this. I have an array of ArrayList like this:
ArrayList<Car>[] cars = new ArrayList[2];
Later in my program I am iterating over that array and I need to remove some objects from the ArrayList. However, since I cannot iterate over a list and remove the elements at the same time, I have decided to clone the array and remove the objects from the ArrayList of the clone. I noticed though, that the clone is referencing the same objects as the ones from the array. Below is some basic example:
ArrayList<Car>[] cars = new ArrayList[2];
cars[0] = new ArrayList<Car>();
cars[0].add(new Car("black"));
cars[0].add(new Car("white"));
cars[1] = new ArrayList<Car>();
cars[1].add(new Car("green"));
cars[1].add(new Car("red"));
ArrayList<Car>[] carClone = cars.clone();
carClone[0].remove(0); // removes the objects from the ArrayList of clone as well as the ArrayList of the "real" array
In the above example you can see that it doesn't just remove the object from the clone, but also from the array. How can I overcome this problem? Any thoughts?

difference between arraylist = arraylist and arraylist.addAll(arraylist)

What the difference between assigning an arraylist to another and using method addAll between two arraylists?
1 > arrayList = arrayList; //should assign value of later arrayList to the first.
2> arrayList.addAll(arrayList) //add all the data of the later list to first.
the first completely replaces the data in the list ?
the second one for appending data in the list(if it already has any) ???
if i do arrayList.add(arrayList) without assigning any data to the first list, will it insert any data ?
I did the following code for testing and found results that i do'not really know.
secondList.add("1");
secondList.add("2");
firstList = secondList;
Log.i("CHECK","first list = "+ firstList);
firstList.addAll(secondList);
Log.i("CHECK","Firs list add : "+firstList);
firstList.clear();
firstList.addAll(secondList);
Log.i("CHECK","Firs list add 2 : "+firstList);
Result were :
CHECK: first list = [1, 2]
CHECK: Firs list add : [1, 2, 1, 2]
CHECK: Firs list add 2 : []
i was expecting the last log to have result like : [1,2]
as mentioned in docs.oracle.com
addAll- Appends all of the elements in the specified collection to the
end of this list, in the order that they are returned by the specified
collection's Iterator.
and if there's no data in the list ? then what will addAll DO ?
When you do:
firstList = secondList;
What you are saying is actually "to make firstList and secondList refer to the same list". After the line is executed, there will only be one list and two variables both refer to that list.
This is why after you cleared firstList, secondList lost all the elements as well. They refer to the same thing. This has nothing to do with addAll. When you called firstList.addAll(secondList), you are basically adding appending an empty list to another empty list, which results in an empty list.
when you use arrayList = arrayList2; then you are assigning the reference of arrayList2 in first list. That means they are referring to the same list.
and when you use arrayList.addAll(arrayList2) then they are two different list reference.
Now come back to your code (lets denote firstlist as f, second as s)
secondList.add("1"); // f={}, s = {1}
secondList.add("2"); // f={}, s = {1,2}
firstList = secondList; // f= s = {1, 2}
Log.i("CHECK","first list = "+ firstList); // so printing 1,2
firstList.addAll(secondList);// it is actually adding itself.. so f= s = {1,2,1,2}
Log.i("CHECK","Firs list add : "+firstList);
firstList.clear(); // clear boths as s = f
firstList.addAll(secondList); // as boths are blank so overall blank
Log.i("CHECK","Firs list add 2 : "+firstList);
I learned about this in class, Java doesnt really specify when it passes by value or passes by reference, but for the sake of arrayList's, they are pass by reference unless you specifically create new elements. When you say
firstArray = secondArray;
firstArray gets the memory address of the second array, therefore when you cleared the first array, you actually cleared the memory which the second array also shares.
Good luck!

Adding elements to List<List<String>> from an array list

I want to add COPIES of data to my List but when I use .add, it adds a reference and not a copy. I'll try to explain what I mean.
List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
//rowFormattedMatches.clear();
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);
I've written my code outside of a loop to try to explain myself better. I want to add 3 elements to an ArrayList (of which the elements come from a normal array) then add that ArrayList to a list of lists. When the ArrayList is added to the list, I want to clear it and refill it with 3 more elements and then add it to the next index of the List. The problem is once I clear it, the data is removed from the list. If I don't clear it, the list has 6 elements at each index when there's only supposed to be 3. What should I do?
Apologies for my possibly confusing explanation.
The call of clear() empties the list. As you are using the same instance for each iteration, this will not work. What you can do instead of clearing the list is create a new instance:
List<List<String>> formattedTempMatches = new ArrayList<>();
ArrayList<String> rowFormattedMatches = new ArrayList<>();
rowFormattedMatches.add(matchesArray[0]);
rowFormattedMatches.add(matchesArray[1]);
rowFormattedMatches.add(matchesArray[2]);
formattedTempMatches.add(rowFormattedMatches);
rowFormattedMatches = new ArrayList<>(); // new instance of an empty list
rowFormattedMatches.add(matchesArray[3]);
rowFormattedMatches.add(matchesArray[4]);
rowFormattedMatches.add(matchesArray[5]);
formattedTempMatches.add(rowFormattedMatches);

ArrayList. Strange things

I have the code:
private class Record {
byte year;
float val;
}
Record record=new Record();
List<Record> recList = new ArrayList<Record>();
...
//now I add first element to array list
record.year=12;
record.val=55;
recList.add(record);
//now I add second element to array list
record.year=13;
record.val=77;
recList.add(record);
As you see I add different elements.
But as a result all elements in array list are the same.
So adding 2-nd, 3-d... element changes all previous elements
to the values of last "record".
What's wrong? Thanks?
An ArrayList keeps a list of references to objects. You're always modifying the same original object which means the reference is the same, but its values differ.
You can fix it by explicitly assigning a new instance to the record variable:
record.year=12;
record.val=55;
recList.add(record);
record = new Record();
record.year=13;
record.val=77;
recList.add(record);
You need to instantiate new objects so they are physically different objects. Right now, you only have one object that is in the ArrayList multiple times.
Record record = new Record();
Also, you should add hashCode() and equals() to Record since you are working with collections.
As you see I add different elements
No, you just edited old Record object and added it again. Each time before you add Record object you need to crate new one.

java two dimensional array add method

this is my first question on Stack! I'm having a small problem populating a 2d arraylist with arraylists, using the add method. After adding my first arraylist to the 2d arraylist, and attempting to repopulate the SAME 1d arraylist, adding this 1d arraylist again to the 2d arraylist seems to alter the first element of the 2d arraylist I added...
ArrayList<ArrayList<String>> twoDArray = new ArrayList<ArrayList<String>>();
ArrayList<String> oneDArray = new ArrayList<String>();
oneDArray.add("a");
twoDArray.add(oneDArray);
System.out.println("First element in twoDArray: " + twoDArray.get(0)); //prints [a]
twoDArray.add(oneDArray);
oneDArray.clear();
oneDArray.add("b");
twoDArray.add(oneDArray);
System.out.println("First element in twoDArray:" + twoDArray.get(0)); //prints [b]
In practice, oneDArray is actually a local variable inside an iterator, hence why I am attempting to re-use it. I add elements to oneDArray, and when a check returns true, I add oneDArray to twoDArray, empty oneDArray, then continue this process, creating a list of lists.
Would this be to do with twoDArray.get(0) actually holding a pointer to oneDArray, and not it's actual value? If so, how might I work around this issue?
Any help would be much appreciated :)
EDIT: solution to above issue
ArrayList<ArrayList<String>> twoDArray = new ArrayList<ArrayList<String>>();
ArrayList<String> oneDArray = new ArrayList<String>();
oneDArray.add("a");
twoDArray.add(new ArrayList<String>()); // Create new arraylist inside twoDArray
twoDArray.get(0).add(oneDArray.get(0)); // Populate new arraylist rather than hold reference to oneDArray
oneDArray.clear();
oneDArray.add("b");
twoDArray.add(new ArrayList<String>());
twoDArray.get(1).add(oneDArray.get(0));
Yes if you are not creating oneDArray inside the loop and merely clearing it will be overwritting on each iteration, that is why the elements are lost. This is indeed because you have the same reference to the same inner arraylist. You should do ArrayList<String> innerToBeAdded = new ArrayList<>() inside your loop conditional to create a new arraylist.
You say " I add oneDArray to twoDArray, empty oneDArray, then continue this process, creating a list of lists", but what you are really doing is adding the same array multiple times to the twoDArray. Because the exact same array is added multiple times to the twoDArray, when you clear() it, it clears all the values, and when you add a value to oneDArray it will appear in all the places in twoDArray.
Instead of clearing the array, what you should do is create a new instance array: oneDArray = new ArrayList<String>(); This will create a different array as each member of twoDArray

Categories

Resources