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

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

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.

What is the different between creating a list and inserting a value at the same time vs. in 2 steps?

I am trying to give value pre[1] to a new list by using List <Integer> list = new ArrayList(pre[1]);, but I got an empty list .
When I make this into 2 steps: first create an empty list1, then add pre[1] to my list1 , it works: list1 contains 2.
Can anyone tell me why?
I was expecting the same result.
I was thinking List <Integer> list = new ArrayList(pre[1]); is creating a list, and initializing the value to pre[1], but is not working, what is the problem??
int[] pre =new int []{1,2,3};
List <Integer> list = new ArrayList(pre[1]);
List <Integer> list1 = new ArrayList();
list1.add(pre[1]);
Please read the documentation of ArrayList's constructors.
TL;DR: There is no constructor that receives the new element(s) that the initialized ArrayList should contain.
The constructor that you're calling is the one that receives an integer as argument, which has its capacity defined according to the argument (i.e. pre[1] or 2 in your case).
The constructor of ArrayList receives initialCapacity not the element.
So in your case you are creating List with initialCapacity 2 i.e pre[1].
public ArrayList(int initialCapacity)
You may want to try List.of in java9
List.of(pre[1], pre[2]);

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

Collections.sort() affects all ArrayLists. How do I sort only one list and not the others?

I have three ArrayLists:
One is used for storing user input in the order they were entered, located in the main class.
Second one is exactly the same as the first one, but it is passed into a method called remTrip to be copied and will return the result.
Third one is list1 in the code below, which is the one being processed.
public static ArrayList<String> remTrip( ArrayList<String> a){
//code here
ArrayList<String> list1 = a;
Collections.sort(list1);
//code to remove triplicates from the list and returns the result
}
I wanted to keep the first ArrayList<String> in the same order it was (i.e. {"dog", "cat" , "tiger", "cat", "cat"} ), but apparently the Collections.sort() sorts all of the ArrayLists.
How do I sort only one of the list and not the others?
The problem is not how Collections.sort() works. The problem is that instead of creating a copy of your list, you set the new list equal to your list. This means that they both point to the same object, sorting one will sort the other because they are the same thing. To solve this set list1 to a copy of a instead of setting them equal.
You should be able to do
ArrayList<String> list1 = new ArrayList<String>(a);
Three arralists you're talking about are not 3 different arraylists. They're just three different references to the same arraylist.
What you're doing essentially is -
List list01 = new ArrayList();
List list02 = list01;
List list03 = list01;
What you want is -
List list01 = new ArrayList();
List list02 = new ArrayList(list01);
List list03 = new ArrayList(list01);
But you should remember, this way will give you a copy of your List, not all it's elements. So, if you change one of the elements in your copied List, it will be changed in your original List too.
How to solve it - Hint copy constructor.

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