Clear() function for Arraylist in Arraylist - java

I am trying to add an arraylist in an arraylist in a for loop. When I clear the data in second one, it clears in second arraylist data in first arraylist. Let me explain with code:
ArrayList arrTemp = new ArrayList();
ArrayList arrTemp2 = new ArrayList();
for(int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; j++)
{
//Here I add some strings in arrTemp
}
arrTemp2.add(arrTemp); //I will add arrTemp 10 times with different data in it to arrTemp2
arrTemp.clear(); //Everytime I want to clear the arrTemp
//But when I clear it, it also clears already added arrTemp in arrTemp2
}
I want it to have 10 different arrTemp in arrTemp2

for(int i = 0; i < 10; i++)
{
arrTemp = new ArrayList();
for(int j = 0; j < 10; j++)
.....
You will have different array for each i.

arrTemp2.add(arrTemp);// will add arrTemp object's reference to your arrTemp2.
So, once you clear arrTemp, you actually will clear() the space being pointed by arrTemp.
use Generics with addAll(), like this:
public static void main(String[] args) {
ArrayList<Integer> al = new ArrayList<Integer>();
al.add(1);
al.add(2);
ArrayList<Integer> al2 = new ArrayList<Integer>();
al2.add(3);
al.addAll(al2);
al2.clear();
System.out.println(al);
}
O/P :
[1, 2, 3]
Your case :
public static void main(String[] args) {
ArrayList al = new ArrayList();
al.add(1);
al.add(2);
ArrayList al2 = new ArrayList();
al2.add(3);
al.add(al2);
al2.clear();
System.out.println(al);
}
O/P :
[1, 2, []] // 3rd item is considered as an Object

I'm not positive, but it seems to me that your addTemp2.add(arrTemp) is not working as intended. Have you tried debugging and checking whether arrTemp2 is actually being populated with something after that line fires? Looking at the documentation (below) for ArrayLists, I think you might want addAll instead. Alternately, you could iterate over arrTemp and add each element individually to arrTemp2 before you clear arrTemp.
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

Easy..
Replace
arrTemp.clear(); with arrTemp = new ArrayList();

Related

Understanding the logic behind clear() in ArrayList

I am using below program to find the subsequences in an given given list. When I am using clear() , the values in li is also getting cleared. Hence, I am creating a new reference everytime.
I wanted to understand the logic behind this. Am I using it wrong? Or it is the reference that I am adding to my li?
public static int getTheSubseq(List<Integer> AList){
// int[][] subsequences = new int[][];
List<List<Integer>> li = new ArrayList<>();
List<Integer> temp = new ArrayList<>();
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
temp = new ArrayList<>();
//temp.clear();
}
}
System.out.println(li);
return 1;
}
Regardless of whether or not you are calling temp.clear(), if you add to li multiple times a reference to the same List object, li will contain multiple references to the same List object, which means li.get(0) == li.get(1), li.get(0) == li.get(2), and so on...
Making changes in one of these inner Lists will be reflected in all the other inner Lists, since there's just one List referenced multiple times.
Therefore, assigning a new ArrayList instance to temp in each iteration of your loop (before adding it to li) is the right thing to do.
I'd make a slight change though - create the new inner List just before adding it to the outer List:
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
List<Integer> temp = new ArrayList<>();
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
}
}
Adding the element to li doesn't make a copy. So when you call clear() you'll have both temp and an element inside li that point to the same object.
You may want to just declare temp inside the inner loop, so you get a fresh one every time without needing to call clear().
When you call .clear() (or any other method for that matter), you're operating on the same refernece.
Here, if you don't create a new list each iteration, you're adding the list referenced to by temp to li. When you call clear(), they are "all" cleared, since they all point to the same object.
When you create a new list each iteration, you have different objects, and can operate on them independently.
Try doing this:
public static int getTheSubseq(List<Integer> AList){
// int[][] subsequences = new int[][];
List<List<Integer>> li = new ArrayList<>();
List<Integer> temp;
for (int i = 0; i < AList.size(); i++){
for(int j =i+1; j < AList.size(); j++){
temp = new ArrayList<>();
temp.add(AList.get(i));
temp.add(AList.get(j));
li.add(temp);
}
}
System.out.println(li);
return 1;
}

How do I loop thorough a 2D ArrayList in Java and fill it?

I am trying to use 2D arrayLists in Java.
I have the definition:
ArrayList<ArrayList<Integer>> myList = new ArrayList<ArrayList<Integer>>();
How can I loop through it and enter in numbers starting from 1?
I know that I can access a specific index by using:
myList.get(i).get(j)
Which will get the value. But how do I add to the Matrix?
Thanks
You can use a nested for loop. The i-loop loops through the outer ArrayList and the j-loop loops through each individual ArrayList contained by myList
for (int i = 0; i < myList.size(); i++)
{
for (int j = 0; j < myList.get(i).size(); j++)
{
// do stuff
}
}
Edit: you then fill it by replacing // do stuff with
myList.get(i).add(new Integer(YOUR_VALUE)); // append YOUR_VALUE to end of list
A Note: If the myList is initially unfilled, looping using .size() will not work as you cannot use .get(SOME_INDEX) on an ArrayList containing no indices. You will need to loop from 0 to the number of values you wish to add, create a new list within the first loop, use .add(YOUR_VALUE) to append a new value on each iteration to this new list and then add this new list to myList. See Ken's answer for a perfect example.
Use for-each loop, if you are using Java prior 1.5 version.
for(ArrayList<Integer> row : myList) {
for(Integer intValue : row) {
// access "row" for inside arraylist or "intValue" for integer value.
}
}
Assuming the matrix is not initialized,
int m = 10, n = 10;
ArrayList<ArrayList<Integer>> matrix = new ArrayList<ArrayList<Integer>>();
for (int i = 0; i < m; i++) {
List<Integer> row = new ArrayList<Integer>();
for (int j = 0; j < n; j++) {
row.add(j);
}
matrix.add(row);
}

How can I get arraylist out of the for loop?

I have
List<ABC> abcList = new ArrayList<ABC>();
ABC abc = new ABC();
for (int i = 0; i < abcList.length; i++) {
abc.setX(5)
abc.setY(5-10) // just an example to easy to understand
abcList.add(abc)
}
System.out.println(Integer.toString(offsetList.get(0).getY()));
I want the result is -5, but the log prints 0 and it's the same for the remains objects. I am learning java, so please tell me how can I get the arraylist out of the for loop?
You have to re-initialise your abc varible each time.
Also your arrayList is empty in the beginning. it will never get into the for-loop.
List<ABC> abcList = new ArrayList<ABC>();
for (int i = 0; i < 10; i++) {
ABC abc = new ABC();//You have to re-initialise your variable each time.
abc.setX(i);
abc.setY(i - i * 2);
abcList.add(abc);
}
System.out.println(abcList.get(0).getY());
Just remove the for loop and you have expected answer there.
For adding a single element to a list, you don't need a for loop.

Adding values from an arraylist of an arraylist

Does anyone know how I can sum the values in an arraylist contained inside an arraylist?
For e.g.
ArrayList<Double> arr1=new ArrayList<Double>;
ArrayList<Double> arr2=new ArrayList<Double>;
Let say: arr1=[4.5,6.7,8.9,7.3,4.5]
arr2=[5.6,7.8,1.3,4.5,3.2]
ArrayList<ArrayList<Double>> arrayListOfarr1_arr2=new ArrayList<ArrayList<Double>>();
arrayListOfarr1_arr2.add(arr1);
arrayListOfarr1_arr2.add(arr2);
How can I it such that both of the arrayList values can be added together when it points to the same index inside the arrayList the contains them?
For e.g.
sum_of_arr1_arr2=[10.1,14.5,10.2,11.8,7.7]
You just need to iterate through your array lists, like so
List arr3<Double> = new ArrayList<Double>();
// Set the loop to the size of the smallest array
int loopSize = arr1 < arr2 ? arr1.size() : arr2.size();
for (int x = 0 ; x < loopSize ; x++) {
arr3.add(arr1.get(x) + arr2.get(x));
}
Also, in general we should always try to use List<T> myList = new ArrayList<T>(); instead of ArrayList<T> myList = new ArrayList<T>();.

Clean way to initialize an arraylist

I want an Arraylist in Java, which I want to fill with 10's
ArrayList<Integer> list = new ArrayList<Integer>(100);
for (int i = 0; i < 100; i++) {
list.add(10);
}
I'm going to have to initialize a lot of Arraylists, so I was wondering if there is there a clean way to do this without a for loop?
You can use Collections.nCopies:
ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 10));
This will initialize list with 100 10's.
ArrayList<Integer> list = new ArrayList<Integer>(100);
for (int i = 0; i < list.size(); i++)
{
list.add(10);
}
list.size() will be 0 here, so this is why your code does not work. size keeps track of how many elements are currently in the list, not the capacity.
If you want the ArrayList to be initialized with all 10s, you can use:
ArrayList<Integer> list = new ArrayList<Integer>(Collections.nCopies(100, 10));
Edit: You said later that you didn't want a for loop, but to fix your code, just replace list.size() with 100.

Categories

Resources