Convert ArrayList<double[][]> to double[][] - java

I have an array list where each element of it is a double[1][3] list. Now if the array list contains n members, I want my output to be a list of size double[n][3]. Based on this post I tried the following:
ArrayList<double[][]> testArray = new ArrayList<double[][]>();
double [][] testList = new double[testArray.size()][];
for(double [][] temp : testArray){
// temp is a list?
}
I also tried the following:
double [][] test = new double[testArray.size()][3];
test = testArray.toArray(test);
None of them are working for me. Any help would be much appreciated. Thanks.

If all arrays in list have 1st dimension size equal to one then you can try:
ArrayList<double[][]> testArray = new ArrayList<double[][]>();
int testArraySize = testArray.size();
double [][] testList = new double[testArraySize][];
for (int i = 0; i < testArraySize; i++) {
testList[i] = testArray.get(i)[0];
}
I think it's pretty straightforward so I'll comment only on that:
get(i)[0]
This takes i-th element from list, which is a two dimensional array and then [0] operator is invoked which accesses second dimension which is what we want to copy to target array. It all works under requirement that first dimensions of arrays in list have size equal to one.
// temp is a list?
No, it is a two dimensional array - it's a list element.
Your second snippet have no chance of working in that case since toArray creates an array in which every array element is an element from list so three dimensional array would be created. But still if you would use that method then to you would have to provide one dimensional array as a parameter to that method (not two dimensional) because toArray takes and returns one dimensional array. In your case that would be one dimensional array in which every element is a two dimensional array which results in having three dimensional array which is not what you want.

You've got a nice start going on with your for loop. All you need now is to copy content from temp to testList, like this:
List<double[][]> testArray = new ArrayList<double[][]>();
double [][] testList = new double[testArray.size()][];
int pos = 0;
for(double [][] temp : testArray){
testList[pos++] = temp[0];
}
This creates a shallow copy. Any modifications to values of testArray will be "visible" through testList array.
Note on naming: testArray is actually a list, while testList is actually an array.

ArrayList<double[][]>() : means a single dimension array in which each element is a double dimension array.
There are multiple double[][] elements.
If you want a single element, then you can get it with .get(index) method.
If you want to convert ArrayList<double[][]> to double[][][] then slightly change your code as
double[][][] testList = new double[testArray.size()][][];
for(int i=0;i<testArray.size();i++){
testList[i] = testArray.get(i);
}

Related

Java, search for elements of an string array and write them into another array

I am looking for a solution how I can get an array of contains from another one.
For example:
I have an array:
Array= [S1!!T1, S1!!T2, S1!!T3, S2!!T1, S2!!T2, S3!!T1, S3!!T2, S3!!T3]
I am looking for elements in "Array" that contain "S2" and write them to another one. so i should get:
Result = [S2!!T1, S2!!T2]
I already tried the Arrays.asList(I).contains(i) but this is not what i am lookig for i think.
If you wish to copy elements of one array to another, first thing you need to do is loop through the elements of one array and if you find a match then store it into another array.
Let's say you have the following array:
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
We don't know how many of those elements in the array are going to match until we loop through them so we have two choice:
Create another array with the same size as arr (cause some null values in array if not all entries of arr re matched)
Use ArrayList and then later convert ArrayList to array if needed
See below:
public static void main(String[] args) {
String[] arr = new String[]{"S1!!T1", "S1!!T2", "S1!!T3", "S2!!T1", "S2!!T2", "S3!!T1", "S3!!T2", "S3!!T3"};
List<String> s2List = new ArrayList<String>();
//loop through arr and for each element check if it contains S2
for(int i = 0; i < arr.length; i++) {
//if it contains S2 then it returns true and we add it to list
if(arr[i].contains("S2")) {
//add to list the element
s2List.add(arr[i]);
}
}
//print the list for testing
System.out.println(s2List);
//if you wish to store the elements to array then
//now we know how many matched, so we can create array with the
//size of elements in s2List
String[] sArr = new String[s2List.size()];
//Here loop through the list and assign values to array
for(int i = 0; i < s2List.size() ; i++) {
sArr[i] = s2List.get(i);
}
//print the array
System.out.println(Arrays.toString(sArr));
}
You can also use other methods that convert a List to array directly but, above should give you an idea of how to resolve the question you asked.
You could use Java 8 streams
String[] filtered = Stream.of(strings).filter(s -> s.contains("S2")).toArray(String[]::new);

Not able to understand array declaration int[] it2= new int[][]{{1}}[0];

Please someone can help me understanding the way this array has been created.
int[] it2= new int[][]{{1}}[0];
it2 is one dimension array and on the right hand we have weird type of initialization.
The code compiles fine, but I am able to understand how it is working.
Break the expression in parts to better understand them:
int[] first = new int[]{1}; // create a new array with one element (the element is the number one)
int[][] second = new int[][]{first}; // create an array of the arrays. The only element of the outer array is the array created in the previous step.
int[] third = second[0]; // retrieve the first (and only) element of the array of array `second`. This is the same again as `first`.
Now we will merge those expressions again. First we merge first and second:
int[][] second = new int[][]{new int[]{1}};
int[] third = second[0];
OK, no big deal. However the expression second can be shortend. The following is equivalent:
int[][] second = new int[][]{{1}};
int[] third = second[0];
Now we merge second and third. We can directly write:
int[] third = new int[][]{{1}}[0];
And there we are.

How to handle an object array of Object Arrays

I have this code:
Object [] array=new Object array [5];
array[0]= new Object[3];
array[1]=new Object [10];
array[2]=new Object [7];
...
How can I access the 5th element of array[1].
If it was a 2D array I would say:
Object o=array [1][5];
but I don't want 2D array because I don't want to waste memory since the size varies from array to array.
It would be great if someone could answer me this question..
Btw I don't want to use vectors etc...
Thank you
You could do it like this:
//This creates a 5 by ? array
Object[][] array = new Object[5][];
array[0] = new Object[3];
array[1] = new Object[10];
array[2] = new Object[7];
....
edit (thanks to the commenters) :
array is an array of arrays. Each element in array refers to an array of Objects.
The memory is not wasted on having more elements than needed.
It will look like this
[a00][a01][a02]
[a10][a11][a12][a13][a14][a15][a16][a17][a18][a19]
[a20][a21][a22][a23][a24][a25][a12]
If you now would like to access the 6th element of the 2nd array you would do this:
Object myObj = array[1][5];

Java ArrayList for integers

I have values that I'd like to add into an ArrayList to keep track of what numbers have shown up.
The values are integers so I created an ArrayList;
ArrayList<Integer[]> list = new ArrayList<>();
int x = 5
list.add(x);
But I'm unable to add anything to the ArrayList using this method.
It works if I use Strings for the array list. Would I have to make it a String array and then somehow convert the array to integers?
EDIT: I have another question. I'd like the list to only hold 3 values. How would I do so?
List of Integer.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
You are trying to add an integer into an ArrayList that takes an array of integers Integer[]. It should be
ArrayList<Integer> list = new ArrayList<>();
or better
List<Integer> list = new ArrayList<>();
you are not creating an arraylist for integers, but you are trying to create an arraylist for arrays of integers.
so if you want your code to work just put.
List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);
you should not use Integer[] array inside the list as arraylist itself is a kind of array. Just leave the [] and it should work
Actually what u did is also not wrong your declaration is right . With your declaration JVM will create a ArrayList of integer arrays i.e each entry in arraylist correspond to an integer array hence your add function should pass a integer array as a parameter.
For Ex:
list.add(new Integer[3]);
In this way first entry of ArrayList is an integer array which can hold at max 3 values.
The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values.
Just use
List<Integer> list = new ArrayList<>();
to create the ArrayList and it will work.
Here there are two different concepts that are merged togather in your question.
First : Add Integer array into List. Code is as follows.
List<Integer[]> list = new ArrayList<>();
Integer[] intArray1 = new Integer[] {2, 4};
Integer[] intArray2 = new Integer[] {2, 5};
Integer[] intArray3 = new Integer[] {3, 3};
Collections.addAll(list, intArray1, intArray2, intArray3);
Second : Add integer value in list.
List<Integer> list = new ArrayList<>();
int x = 5
list.add(x);
How about creating an ArrayList of a set amount of Integers?
The below method returns an ArrayList of a set amount of Integers.
public static ArrayList<Integer> createRandomList(int sizeParameter)
{
// An ArrayList that method returns
ArrayList<Integer> setIntegerList = new ArrayList<Integer>(sizeParameter);
// Random Object helper
Random randomHelper = new Random();
for (int x = 0; x < sizeParameter; x++)
{
setIntegerList.add(randomHelper.nextInt());
} // End of the for loop
return setIntegerList;
}

Is ArrayList of ArrayList similar to a 2D array in java?

Is an
ArrayList<ArrayList<Integer>> numbers; like a 2D array of ints int[][] numbers;?
Or are these stored completely different from one another?
It is a structure with two dimensions, so it is [][]-like, yet there is one very important difference: if you allocate a two-dimensional array in one step you'll get same size in the second dimension for all elements of the first dimension:
int[][] arrayOfInts = new int[5][4];
for (int[] second : arrayOfInts) {
System.out.println(second.length);
}
prints 5 times a "4".
Using ArrayList of ArrayLists all elements of the second dimension may have different size.
As pointed out by jlordo: an array of ints may also have the second dimension of different lengths if it is created dynamically:
int[][] anotherArray = new int[5][];
for (int i=0; i<5; i++) {
anotherArray[i] = new int[i];
}
in which case a NullPointerException can be throws if the second dimension were accessed before being intialized, like:
int[][] yetAnotherArray = new int[5][];
System.out.println(yetAnotherArray[2][3]);
The other difference: after allocating a int[x][y] the memory for all its elements in both dimension is allocated from the very first moment. In ArrayList of ArrayLists the memory needed for the lists is allocated, but the memory needed for its elements will be used not before you create their content. So a similar code as before will print nothing, because at the beginning there will not be even a single element in the first ArrayList.
In order to have the second dimension you first have to create all ArrayLists of the second dimension:
ArrayList<ArrayList<Integer>> arrayOfArrays = new ArrayList<ArrayList<Integer>>();
for (int i=0; i < 5; i++) {
arrayOfArrays.add(new ArrayList<Integer>();
}
Further on the accessing side:
int[][] arrayOfInts = new int[5][4];
System.out.println(arrayOfInts[2][3]);
prints 0 because all of the memory is already allocated. The access is safe both in addressing the dimensions and its value, because it is of a primitive type.
ArrayList<ArrayList<Integer>> arrayOfArrays = new ArrayList<ArrayList<Integer>>();
for (int i=0; i < 5; i++) {
arrayOfArrays.add(new ArrayList<Integer>();
}
System.out.println(first.get(2).get(3));
throws ArrayOutOfBoundsException. You have to check the size of the elements before accessing them.
Now there is also one important difference between int[][] and Integer[][]: primitive types always have values, so after allocating int[4][5] you'll have 0 for unitialized elements. Integer[4][5] contain objects, so unitialized elements will have null instead.
It is similar to Integer[][], which is somewhat different to int[][].
Also ArrayList provides additional facilities over what an array does, such as the ability to grow dynamically, and manage separate notions of size and capacity.
Not fully sure but the memory allocation would be different in both cases. The primitive array int[][] will be allocated in stack while the ArrayList<ArrayList<Integer>> will be allocated in Heap.

Categories