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

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.

Related

How do I add arrays to an Arraylist of Arrays (Arraylist<Integer[]>)

I want to save the steps pf my player-character in a Sokoban-game.
So at first i want to fill an Array of int x and y, called "pos" with the actual position of the character.
And than i want to add this array to an ArrayList of Arrays, called "moves".
Array for one player-position:
int[] pos = new int [2];
ArrayList for all steps, the player made in the level:
Arraylist<Integer[]> moves = new ArrayList<>();
"int[]" makes an error, if placed inside the pointy brackets at the ArrayList.
How do i add the Array pos to the ArrayList moves?
This works completely fine with int[]. However int[] != Integer[], Use same in both places.
int[] pos = new int[2];
ArrayList<int[]> arrayList = new ArrayList<>();
pos[0] = 1;
pos[1] = 2;
arrayList.add(pos);
System.out.println(arrayList.get(0)[0]+ " "+ arrayList.get(0)[1]);
int and Integer are two different things (I struggled with this as well when I first learned Java a long time ago.
int is a so-called primitive datatype, which means it is not an object. Integer is a wrapper class, basically a class whose only purpose is to contain an
int so that it can be handled as an object. Since Java 5, there is "autoboxing", which means you can assign int values to Integer variables and vice versa, and the compiler will handle it silently. This tends to muddle the difference, but it still is there and important - such as in this case.
So if you want to store instances of int[] in an ArrayList, you need an ArrayList<int[]>, not an ArrayList<Integer[]>.
However, it is impossible to have an ArrayList<int> because ArrayList can only store Objects (the generic types exist only for the compiler), not primitives.
Oh yes, and to add an element to the list, use
Arraylist<int[]> moves = new ArrayList<>();
arrayList.add(pos);
You could have found this in the API doc for ArrayList - you should really learn to use the API doc, you will need it all the time to answer questions such as this.
You can also make class (for example Pos) and make x and y as attributes and make constructor. The you can make the type of arraylist is Pos
ArrayList arrayList = new ArrayList<>();
arrayList.add(new Pos(3,2));

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

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

add two dimensional list to multidimensional arraylist

I have got a loop with 2d list where I delete and add elements and want to add those temporary arraylists to the dimensions of another list.
Example,
// 2d list
List<List<Integer>> p = new ArrayList<List<Integer>>();
// 3d list
List<List<List<List<Integer>>>> list1 = new ArrayList<List<List<List<Integer>>>>();
// this compiles ok
list1.get(0).add(p);
but I get the following error:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
You need to instantiate every list.. not just the one you are trying to access. Meaning that if you have a 2x2 matrix, you need 2 rows = 2 lists, and another list to hold them both, and so on if the matrix starts getting more complex.
List<List<Integer>> matrix = new ArrayList<List<Integer>>();
List<Integer> row = new ArrayList<Integer>();
matrix.add(row);
Your "list1" object is actually 4d in your example, but those are not initialized, so when you ask "list1" to get the first (three dimensional) list inside, it does not exist at all (arrays in Java starts at 0 size), so there is nothing to add there.
You could do something like:
List<List<List<List<Integer>>>> list1 = new ArrayList<List<List<List<Integer>>>>();
List<List<List<Integer>>>> 3dlist = new ArrayList<List<List<Integer>>>();
list1.add(3dlist)
list1.get(0).add(p);
Now, using multidimensionnal arrays directly like this is not really practical - you may want to encapsulate them in an object.

Store an array within a 2d array Java

So why doesn't this work? Not really sure why this isn't possible- I just want to store an array of size 2 inside a 2d array.
I know this would be equivalent to setting storage[0][0] = array[0] and storage[0][1] = array[1], but just wondering why this is incorrect.
public class Test {
public static void main(String[] args) {
boolean[][] storage = new boolean[10][2];
boolean[] array = new boolean[2];
array[0] = true;
array[1] = false;
storage[0][] = array; //Why can't I do this?
}
}
Thanks in advance
You have a stray pair of brackets in your assignment. Just use
storage[0] = array;
First of all boolean[][] storage = new boolean[10][2] declares an array and initialise it.
So, you have created 11 arrays. One of boolean[] element type and 10 of boolean type.
It's good, If you want to access it's members directly, but if you create an inner array lately with new boolean[], it's an overhead.
Use boolean[][] storage = new boolean[10][]; instead.
Then, you can access it's elements, which are boolean[] type, and assign your array to it.
storage[0] = array;
Your problem is the stray square brackets(as I'm sure you know). Your code should look like this:
storage[0] = array;
The previous answers did not really explain why though, so that's what I'll do.
What your trying to do is make the first position(storage[0]) hold the same value as array. array is 1 dimensional, so it can only be part of storage, which is 2 dimensional.

arrays in android programming

I am new in android programming.
Here is my question
I tried to declare an array before onCreate() method like
int[] userselected;
Note that i want to use this array to store ids of buttons user had pressed.
Then i tried to find no. of elements in this array with
int noOfElements = userselected.length;
which game me an error.
Then I changed declaration to
int[] userselected = {};
it worked, but when i tried to put an id in this array with code
userselected[1] = R.id.textview1;
it again gave me an error.
I also tried declaring array as
int[] userselected = new int[4];
but then, when i tried to find how many elements have already been stored,
userselected.length
always gave number 4.
Please tell me, how can i get what i want
You need to use ArrayList. It will give you a more flexible structure giving your case.
ArrayList<Integer> userselected = new ArrayList<Integer>();
userselected.add(R.id.textview1); //To add id.
int noOfElement = userselected.size(); //to get size
an array is fixed size. so when you declare this array
int[] userselected = new int[4]
you are creating an array with a fixed size of 4. The array index is zero based so its from [0] to [3]. I recommend you use an ArrayList object like the top answer states
when you do this:
int[] userselected = {};
it is the same as this:
int[] userselected = new int[0]; // empty
and you got an error from this:
int[] userselected;
because you have not allocated any space in memory
Java primitive arrays, such as int[], are constant in length and cannot contain more than their initial length. If you need an array that can change in size, you need to use fx. a List implementation. I would suggest you read up on basic Java before you start developing Android, it would save you a lot of time in the long run.
I think this page can help: http://www.javaclass.info/classes/java-array/array-examples-demonstration-and-code-snippets.php
In the array declaration you do, you say that its size is 4 elements, therefore the length method will always return 4.
regards
declare it as a integer array then Add this to your code
Integer a=0;
for (int i=0;i>userselected.length;i++)
{
if(userselected[i]!=null)
{
a++;
}
}
then a will give you the count you need:) cheers:)

Categories