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
Related
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.
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?
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);
How do you add a String[] into a String[] in Java? To be more clear, my desired output is:
String[][] out = {{"A", "AA"},{"B", "BB"}};
I don't know the size of the output array, it can contain more then two elements. Basically, I wanted to do it like this (don't mind the syntax it's a blend of Python):
String [] out;
String[] temp = {"A","AA"};
out.append(temp)
So now out should look like {{"A","AA"}}. Then I can append {"B", "BB"} creating the desire output above? This is what my thought was, but I'm not sure if it can be done. I am more experienced with Python and it can be done in Python, but I am wanting to do this in Java. Any ideas?
As in the comment mentioned, you can use the List to store all the array values inside.
It is when you put in:
List<String[]> list = new ArrayList<>();
String[] array = {"A", "B"};
list.add(array);
...
And it is when you get out:
String[] array = list.get(0 /*i*/);
Try using List for this purpose as you would have more operations to perform on Lists than an Array.
List<List<String>> out = new ArrayList<>();
List<String> temp = new ArrayList<String>();
temp.add("A");
temp.add("AA");
out.add(temp);
Read through the Javadocs for more on this.
You can either use List or ArrayList that dynamically grows.
ArrayList al = new ArrayList();
The ArrayList class extends AbstractList and implements the List interface. ArrayList supports dynamic arrays that can grow as needed.
Standard Java arrays are of a fixed length. After arrays are created, they cannot grow or shrink, which means that you must know in advance how many elements an array will hold.
Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array may be shrunk.
For differences between List and ArrayList Type List vs type ArrayList in Java
Detailed Methods of ArrayList
You could try this way too if you exactly want to add dynamic array of Strings into another dynamic array.
List<List<String>> addresses = new ArrayList<List<String>>();
ArrayList<String> singleAddress = new ArrayList<String>();
singleAddress.add("17 Fake Street");
singleAddress.add("Phoney town");
singleAddress.add("Makebelieveland");
addresses.add(singleAddress);
Because in Java, Array is a fixed length data structure so you should try java List which supports dynamically insertion and deletion of elements. An example using java.util.ArrayList is following:
java.util.List<String[]> out = new java.util.ArrayList<String[]>();
String[] temp = {"A","AA"};
out.add(temp);//insertion
And using index (started from 0), we can get element like out.get(0); and can remove element like out.remove(0);
please help meto add integer in the ArrayList inside an ArrayList..
Here is the code..
ArrayList<ArrayList<Integer>> player = new ArrayList<ArrayList<Integer>>(10);
ArrayList<Integer> array = new ArrayList<Integer>(10);
array.add(1);
array.add(2);
array.add(3);
array.add(4);
array.add(5);
player.add(array);
player.add(array);
If i check what's inside array and player using debug..
array[1,2,3,4,5]
player[[1,2,3,4,5],[1,2,3,4,5]]
Now, i want to add Integer on player's ArrayList slot 0 using this:
player.get(0).add(6);
but instead of getting of this:
player[[1,2,3,4,5,6],[1,2,3,4,5]]
i got this:
player[[1,2,3,4,5,6],[1,2,3,4,5,6]]
In short, player's ArrayLost slot 0 and slot 1 received the integer that i'ved add..
Please help.. Thanks in advance.. :)
You added the same ArrayList to both entries of the player ArrayList. Both entries of the player ArrayList are exactly the same object.
You should make a second ArrayList:
ArrayList<Integer> array2 = new ArrayList<Integer>();
Then add it as the second item of the player ArrayList.
ArrayList<ArrayList<Integer>> player = new ArrayList<ArrayList<Integer>>(10);
ArrayList<Integer> array = new ArrayList<Integer>(10);
array.add(1);
array.add(2);
array.add(3);
array.add(4);
array.add(5);
ArrayList<Integer> array1 = new ArrayList<Integer>(array);
player.add(array);
player.add(array1);
Already answered...
As others mentioned you actually add the same element to both lists.
If you do not want to fill both ArrayLists with the initial values. You can keep your code and only change the following lines:
player.add(array);
player.add(array);
to:
player.add(array);
player.add(new ArrayList(array)); // alternatively player.add(array.clone());
This makes a new ArrayList to the second entry in players.
The problem with your code is that - when you add the array to player object you pass the same reference of array object.
When you do this player.get(0) you are getting the same object which is ArrayList<Integer> array = new ArrayList<Integer>(10); and then when you do the adding player.get(0).add(6); you are pointing to the reference of array object and java passes objects by reference. see this SO thread
That is because adding array twice to player does not add the values of array to player twice, it only adds two copies of the reference to array to player
player[[1,2,3,4,5],[1,2,3,4,5]]
is really
player[array,array]
You can test this with for example jUnits assertTrue:
assertTrue(player.get(0) == player.get(1))