Temporary ArrayList Replacement [duplicate] - java

This question already has answers here:
Why does one arraylist change when a copy of it is modified
(6 answers)
Closed 3 years ago.
I'm setting a temporary ArrayList equal to a pre-established ArrayList. Changes to the temporary ArrayList seem to also transfer over to the pre-established one. Why does this occur and how can I keep the pre-established ArrayList unchanged?
I know that this phenomenon does not occur in situations that involve ints.
ArrayList<Integer> array = new ArrayList<>();
for (int i = 0; i < 3; i++){
array.add(i);
}
ArrayList<Integer> tempArr = array;
tempArr.remove(0);
I expect array to be [0,1,2], but I get [1,2]. I would like the output to be array = [0,1,2] and tempArr = [1,2].

You just copied the reference of the list to the new variable. That means you have 2 references array and tempArr that are pointing to the same object. You could create a new ArrayList from the old one:
ArrayList<Integer> tempArr = new ArrayList<>(array);

Variables array and tempArr booth point to same instance of ArrayList<Integer> object, hence modifying one will make changes to other.
What you need is to create new instance and then transfer all elements to it:
ArrayList<Integer> array = new ArrayList<>();
for (int i = 0; i < 3; i++){
array.add(i);
}
ArrayList<Integer> tempArr = new Arraylist<>();
tempArr.addAll(array);
tempArr.remove(0);
This code can also be simplified since Arraylist<> is offering you constructor that will add elements from another collection:
ArrayList<Integer> tempArr = new Arraylist<>(array);
tempArr.remove(0);

Related

adding array to linkedList [duplicate]

This question already has answers here:
What causes javac to issue the "uses unchecked or unsafe operations" warning
(12 answers)
Closed 3 years ago.
im getting uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details. error when adding array to linkedlist
Here is my work
LinkedList main_list = new LinkedList();
int arr = new int[2]
arr[0] = 0;
arr[1] = 1;
main_list.add(arr);
The compiler warning messages convey that the operation you are trying to is unsafe!
This comes up in Java 5 and later if you're using collections without type specifiers. (See generics )
Here you are creating a LinkedList() without specifying its type. It means that the compiler can't check that you're using the collection in a type-safe way, using generics.
You should create it like below by specifying its type.
LinkedList<int[]> myList = new LinkedList<>();
You can just have a list of Interger arrays:
LinkedList <int[]> main_list = new LinkedList <>();
int[] arr = {0,1};
int[] arr2 = {2,3};
main_list.add(arr);
main_list.add(arr2);
with this structure all of your Integer arrays will keep their initial boundaries and the result will not be stored in a long flat list. You can access them independently for later use.
You can add it directly by using Arrays.asList(arr). You can directly convert Array into list by using asList() function. Use the following code:
LinkedList main_list = new LinkedList(Arrays.asList(arr));
First convert Array into list and then add it into list. If your Arrays only contain Integers then you create Integer List and array of Integers. Like
Integer[] arr = new Integer[2];
arr[0] = 0;
arr[1] = 1;
List<Integer> main_list = new LinkedList<>();
main_list.add(Arrays.asList(arr));
It will work. Or if you want to save array at every index of lined list then you have to create list of arrays of
Integers. Like
List<Integer[]> main_list = new LinkedList<>();
Integer[] arr = new Integer[2];
arr[0] = 0;
arr[1] = 1;
main_list.add(arr);

Java 2D arraylists

I cant understand 2D arraylists, they are confusing me, I can understand 2D arrays however as I worked with them before in C and in Python as "nested lists"
can someone explain the difference between these 2 codes?
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
ArrayList<String> temp = new ArrayList<String>(); // added ()
temp.add("Hello world.");
temp.add("sup");
biDemArrList.add(temp);
ArrayList<String> it = new ArrayList<String>();
it.add("1");
it.add("0");
biDemArrList.add(it);
System.out.println(temp);
System.out.println(it);
System.out.println(biDemArrList);
and this one :
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
for (int i = 0; i < 12; i++) {
table[0][5].add("0");
}
for (int i = 0; i < 9; i++) {
table[1][1].add("1");
}
System.out.println(table[0][5]);
System.out.println(table[9][9]);
Like in C arrays of non primitive types are not initialized (only arrays of primitive types are...).
ArrayList[][] table = new ArrayList[10][10];
table[0][5] = new ArrayList();
table[1][1] = new ArrayList();
Here you create an array of 100 elements but you only initialize 2 Elements.
ArrayList is resizable-array implementation of the List interface. This class. Most of the developers choose Arraylist over Array as it’s a very good alternative of traditional java arrays.
You can add any object to List, e.g. null, String, Object, String[]. ArrayList<String> also is object, it's means you can add to list.
You said I have ArrayList which can add other ArrayList. The result will be ArrayList<ArrayList>>.
But we want to add only String's to inner ArrayList. And we create ArrayList<String>
So, We have list of string ArrayList<String> which can be added to other list ArrayList<ArrayList>>
ArrayList<ArrayList<String>> mainArrayList = new ArrayList<ArrayList<String>>();
ArrayList<String> subArrayList = new ArrayList<String>();
/* Added elements into subArrayList */
subArrayList.add("Yogesh");
subArrayList.add("Pawar");
ArrayList<String> subArrayList2 = new ArrayList<String>();
/* Added elements into subArrayList2 */
subArrayList2.add("Java");
subArrayList2.add("Programmer");
/* Adding elements into mainArrayList */
mainArrayList.add(subArrayList);
mainArrayList.add(subArrayList2);
for (int i = 0; i < mainArrayList.size(); i++) {
for (int k = 0; k < mainArrayList.get(i).size(); k++) {
System.out.print(" " + mainArrayList.get(i).get(k));
}
System.out.println();
}
The difference between
List of List
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();
and
Array of Array of List
ArrayList[][] table = new ArrayList[10][10];
Is that the second one is not actually two-dimensional, it is three-dimensional. You end up with 10 Arrays of length 10 that you can put ArrayLists into. Where as in the List of List example you have a List you can put other Lists into.
Using the Object[][] or primitive[][] you have to allocate the 2D array with exact number of "rows" and "columns" like new Object[2][8].
On the other hand with ArrayList<ArrayList<...>> try to understand the following code:
ArrayList<ArrayList<String>> biDemArrList = new ArrayList<>();
ArrayList<String> a0 = new ArrayList<>();
a0.add("string_1");
ArrayList<String> a1 = new ArrayList<>();
a1.add("strfdfas");
a1.add("adfadsfasdfasdfasfaf");
biDemArrList.add(a0);
biDemArrList.add(a1);
biDemArrList.stream().forEach(System.out::println);
The first "row" has one element, and the second one has two elements. This is only an example... With arr[][] you cannot achieve this.
What is reason behind this not sure, But i would share my experience here,
Array is the fixed size of data structure, once we initialize the array we can't modify the size. To resolve this we have ArrayList comes to picture. Arraylist has variable lenght.
In your second code snippet, if you are looking for fixed sized of 2D ArrayList, I would suggest to go 2D Arrays.
If you want to get benefit of Collection features, later you can convert Arrays to ArrayList object.

why assign ArrayList to new ArrayList temp

I am looking at the code for Permutations problem on leetcode. For example,
[1,2,3] have the following permutations:
[1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
And I found there is one sentence
ArrayList<Integer> temp = new ArrayList<Integer>(l);
I have no idea why here needs to assign the "l" to "temp". And I tried current.add(l) direclty but gave me the wrong answer. Can you help me with this?
public class Solution {
public ArrayList<ArrayList<Integer>> permute(int[] num) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
//start from an empty list
result.add(new ArrayList<Integer>());
for (int i = 0; i < num.length; i++) {
//list of list in current iteration of the array num
ArrayList<ArrayList<Integer>> current = new ArrayList<ArrayList<Integer>>();
for (ArrayList<Integer> l : result) {
// # of locations to insert is largest index + 1
for (int j = 0; j < l.size()+1; j++) {
// + add num[i] to different locations
l.add(j, num[i]);
ArrayList<Integer> temp = new ArrayList<Integer>(l);
current.add(temp);
//System.out.println(temp);
// - remove num[i] add
l.remove(j);
}
}
result = new ArrayList<ArrayList<Integer>>(current);
}
return result;
}
}
I have no idea why here needs to assign the "l" to "temp"
He's not - that would just be:
ArrayList<Integer> temp = l;
Instead, the code creates a copy of the content of the list l refers to, in a new ArrayList. That means that future changes to the list that l refers to (such as the call to l.remove(j) immediately afterwards) don't affect the new list.
As a simple stand-alone example of that, consider:
List<String> original = new ArrayList<>();
original.add("foo");
List<String> copy = new ArrayList<>(original);
System.out.println(copy.size()); // 1
original.add("bar");
System.out.println(copy.size()); // Still 1
Admittedly the code is written in a very odd manner - until the final statement, result only ever has a single element, so iterating over it is pretty pointless - but I believe that explains the single statement you were asking about.
If you did
current.add(l);
you would be adding the same reference to the ArrayList l to current. So, if you made some changes in one of those lists, both would be modified. In order to avoid that issue, in the line
ArrayList<Integer> temp = new ArrayList<Integer>(l);
you are creating a different ArrayList but with the same content. So, they will be different objects (different references).

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

Issue with ArrayList<ArrayList<String>>

This code was EDITED according to advice from trutheality.
I am having trouble coming up with a good title for this one - if you have a better idea please feel free to change it.
I am creating a two dimensional ArrayList. For that I fill up an ArrayList<String> and then add it to ArrayList<ArrayList<String>>. I do that inside a loop and I was hoping to get a fresh ArrayList<String> every time. This doesn't happen so ArrayList<ArrayList<String>> gets filled up with accumulations of ArrayList<String> because each time I fill up ArrayList<String> it just adds the what it already has.
ArrayList<String> oneD = new ArrayList<String>();
ArrayList<ArrayList<String>> twoD= new ArrayList<ArrayList<String>>();
Cursor tSCursor = retrieveTS(tId);
tSCursor.moveToFirst();
for (int i = 0; i < tSCursor.getCount(); i++)
{
stockId = tSCursor.getString(tSCursor.getColumnIndex("_id"));
oneD.add(sId);
oneD.addAll(retrieveSFinParams(sId));
twoD.add(sFinParams);
tSCursor.moveToNext();
}
I tried sFinParams.clear() but as Java users references in the containers, when I use clear() I also loose the values in the 2D ArrayList.
How can I get a fresh ArrayList each time so when I full up the 2D ArrayList I don't duplicate the contents of the 1D ArrayList?
I appreciate any help,
D
You must create a new instance of ArrayList at each iteration of the loop. Else, you'll keep adding elements to the same inner list, and add this unique inner list multiple times to the outer list.
I am going to imagine that your code was actually
ArrayList<String> oneD = new ArrayList<String>();
ArrayList<ArrayList<String>> twoD= new ArrayList<ArrayList<String>>();
Cursor tSCursor = retrieveTS(tId);
tSCursor.moveToFirst();
for (int i = 0; i < tSCursor.getCount(); i++)
{
stockId = tSCursor.getString(tSCursor.getColumnIndex("_id"));
oneD.add(sId);
oneD.addAll(retrieveSFinParams(sId));
twoD.add(oneD);
tSCursor.moveToNext();
}
The problem is that you are adding the same object (oneD) to twoD repeatedly, instead of creating a new oneD ArrayList for every entry in twoD. The fix is simply that: create oneD inside the loop, so that every iteration works with a different oneD:
ArrayList<ArrayList<String>> twoD= new ArrayList<ArrayList<String>>();
Cursor tSCursor = retrieveTS(tId);
tSCursor.moveToFirst();
for (int i = 0; i < tSCursor.getCount(); i++)
{
stockId = tSCursor.getString(tSCursor.getColumnIndex("_id"));
ArrayList<String> oneD = new ArrayList<String>();
oneD.add(sId);
oneD.addAll(retrieveSFinParams(sId));
twoD.add(oneD);
tSCursor.moveToNext();
}

Categories

Resources