Add Integer in ArrayList<ArrayList<Integer>> - java

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))

Related

Put a list into an array in 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.

Collections sort on a copy of a Arraylist (to keep the orginal order)

If i have an arraylist, and i want both a sorted and unsorted version of it, how can i achive it.
tried with Collections
ArrayList<Integer> someNumbers = new ArrayList<>();
if i then make a new arraylist = someNumbers and sort it. The orginal one gets sorted too ?
ArrayList<Integer> sortedNumbers = someNumbers;
Collections.sort(sortedNumbers);
both list gets sorted.
How can i simply achive what im trying to do ? ( get a sorted copy, and keep the orginal in its orginal ordering )
When you do ArrayList<Integer> sortedNumbers = someNumbers;, you are not creating a new list to sort. You are basically assigning the variable sortedNumbers to the exact same list that someNumbers is assigned to.
To fix it, you can create a new list from your other list. Like this:
ArrayList<Integer> sortedNumbers = new ArrayList<>(someNumbers);
The reason why both lists get sorted is because even you first create a new ArrayList(), you then override this instance with a reference to someNumbers. Therefore when you sort sortedNumbers you actually sort the original list someNumbers.
There are several ways you can achieve your goal:
ArrayList<Integer> sortedNumbers = new ArrayList<>();
sortedNumbers.addAll(someNumbers);
Or you can achieve the same in one step by using the copy constructor:
ArrayList<Integer> sortedNumbers = new ArrayList<>(someNumbers);
You need to make a copy of the list and then sort it, e.g.
ArrayList<Integer> sortedNumbers = new ArrayList<>(someNumbers);
Collections.sort(sortedNumbers);
This uses ArrayList(java.util.Collection) constructor
Just copy the array and sort the copy:
ArrayList<Integer> sortedNumbers = new ArrayList<>(someNumbers);
Collections.sort(sortedNumbers);
You have to copy the ArrayList first to have two versions. Then you can sort one of the two ArrayLists
ArrayList<Integer> someNumbers = ...
ArrayList<Integer> sortedNumbers = new ArrayList<>(someNumbers);
Collections.sort(sortedNumbers);

Is there a way of adding 2 dimmensional array to 2 dimmensional array list in java?

I know how to add a one dimmensional array to a one dimmensional array list
i.e
ArrayList<Integer> arrayList = new ArrayList<Integer>
(Arrays.asList(array));
However,I'm not sure what needs to be done to add a two dimmensional array to a two dimmensional array list .Below posted is the code.
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
ArrayList<Integer> arrayList = new ArrayList<Integer>
(Arrays.asList(myPoints));????
If you want to preserve one-dimensional arrays from int[][] it's basically:
ArrayList<int[]> arrOfArr = new ArrayList<int[]>();
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
arrOfArr.addAll(Arrays.asList(myPoints)); // here's the one-liner doing the job
And if you want to flatten your 2D array to list of integers there's no other way than do it manually by iterating over every element of your array. Which, I suppose, you can.
If Java 8 is an option for you, you could use the Stream API to accomplish what you want in one line:
int[][] myPoints = {{2,3},{4,5},{7,8},{9,10}};
List<List<Integer>> myPointsAsList =
Stream.of(myPoints).map(point -> Arrays.asList(point))
.collect(Collectors.toList());

Manually accessing an ArrayLists with a ArrayList

I'm working with Depth First Search program and I'm trying to create a Adjacency List Representation.
I read through some articles stating that an creating ArrayLists within an ArrayList would be the best representation.
Let's say I initialized the arraylist within a arraylist like so:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
My question is how would you input data into the arraylist MANUALLY. I'm trying to understand the concept of arraylist with an arraylist before I begin my programming. If someone could possibly insert data into this arraylist so I could see the proper way of setting up.
Any additional input on anything I might need or take in consideration is recommended.
BTW: This is not a homework assignment just using personal time looking through my old textbooks.
Let's say you want to add 2 lists, one with 1 and 2 and the other with 10 and 20. A very manual way of adding could be:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
adjList.add(new ArrayList<Integer>()); // initialise new ArrayList<Integer>
adjList.get(0).add(1); // add value one by one
adjList.get(0).add(2);
adjList.add(new ArrayList<Integer>());
adjList.get(1).add(10);
adjList.get(1).add(20);
You could also write it this way:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
ArrayList<Integer> a1 = new ArrayList<Integer>(); // initialise new ArrayList<Integer>
a1.add(1); // add value one by one
a1.add(2);
adjList.add(a1);
ArrayList<Integer> a2 = new ArrayList<Integer>(); // initialise new ArrayList<Integer>
a2.add(10); // add value one by one
a2.add(20);
adjList.add(a2);
Well, a list of a list of Integer objects could be done as such:
List<List<Integer>> adjList = new ArrayList<List<Integer>>();
List<Integer> li = new ArrayList<Integer>();
for (int i = 0; i < 10; i++) {
li.add(i);
}
adjList.add(li);
Add to each sublist, and then add the sublist.
The adjList can contain the elements of the type List<Integer>, so create one and add using add(E element) function as we would for adding an element:
ArrayList<Integer>aList = new ArrayList<>();
adjList.add(aList);
Then to add an element to the element(which has the type List<Integer>) of adjList: you can try getting it using get(index) and add your element:
adjList.get(0).add(10);
adjList.get(0).add(22);
Try adding a second list and get it's index using get(1) and add the Integer element to the list at index 1 as the above example suggest. There are other known function too. Please check the class ArrayList<E> documentation page.
This will help
public static void main(String[] args){
//creating a new ArrayList of List of Integers
ArrayList<List<Integer>> integerListContainer = new ArrayList<List<Integer>>();
//Creating the first child arraylist of Integers
ArrayList<Integer> firstChildintegerList = new ArrayList<Integer>();
//filling the values 1,2,3 in it
firstChildintegerList.add(1);
firstChildintegerList.add(2);
firstChildintegerList.add(3);
//adding this integer list to the parent list
integerListContainer.add(firstChildintegerList);
//Creating the second child arraylist of Integers
ArrayList<Integer> secondChildintegerList = new ArrayList<Integer>();
//filling the values 10,20,30 in it
secondChildintegerList.add(10);
secondChildintegerList.add(20);
secondChildintegerList.add(30);
//adding this integer list to the parent list
integerListContainer.add(secondChildintegerList);
System.out.println("Printing the parent list to see what it has: ");
System.out.println(integerListContainer.toString());
}
Hope it clearly explains what happens

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