I have a code
String ejgStr[] = new String[][]{{null},new String[]{"a","b","c"},{new String()}}[0] ;
System.out.println(ejgStr[0]);
which compiles without error.
From what I understand you can't create an array with non-matching square brackets.
On the left, we have String ejgStr[], which is 1-d array and
On the right, we have String[][]{some array}[0], which is 2-d array
These seem to have different dimensions but why do they successfully compile?
You are assigning a one-dimensional String[] array to the first dimension of an inline two-dimensional String[][] array. Have a look the comments:
String ejgStr[] =
new String[][] {
{ null }, // a null 1D String array
new String[] {"a","b","c"}, // a 1D String array containing a,b,c
{ new String() } // a String array containing empty String
}[0]; // access the { null } 1D array
I expect your assignment to be equivalent to doing this:
String ejgStr[] = { null };
You assign a 1D array to the ejgStr refference. If you look at the end of the first statemend, you will see that you have a [0] index specified which means you will assign the first array (position 0) to your referrence. If you remove the [0] you will receive a compilation error.
new String[][]{...} is a 2D array.
new String[][]{...}[0] is the first element of a 2D array, which is a 1D array.
That's what you're assigning to String ejgStr[].
String ejgStr[] is just a reference to a variable in heap space.
you're pointing to first dimensional of 2D-dimensional array using [0] and make a reference of it in ejgStr[]. this is not common to get 1D from 2D array, but you can do it if you need and of course it wont make compile error.
Related
Curious why declaring an empty array of non-emtpy array(s) is legal in Java:
int[][] array = new int[0][1];
System.out.println(array[][0]); //won't compile.
System.out.println(array[0][0]) //triggers an out of bounds exception.
P.S. I have read the related question on zero-size arrays: Why does Java allow arrays of size 0?
Is this for the same reason?
An int[][] array is an array whose elements are int[] (i.e. its elements are arrays of int).
Just like you are allowed to define an empty array of int elements:
int[] empty = new int[0];
or an empty array of String elements:
String[] empty = new String[0];
You are also allowed to define an empty array of int[1] elements:
int[][] empty = new int[0][1];
Perhaps it's the syntax that is somewhat confusing here.
If it was
int[][] empty = new (int[1])[0]
it would be clearer that you are defining an empty array whose element type is int[1].
However, since the number in the first square brackets represents the number of elements in the outer array, new int[1][0] does not represent an empty array, but an array of a single element (whose single element is an empty int array).
It is legal to define empty arrays in general, no matter what it contains. Thus, it is also legal to have an empty array containing non empty arrays.
Mathematically (group theory) speaking, empty arrays are not only legal, but necessary, since they represent the zero (or neutral) element of array concatenation operation. This also makes it useful for programming (see the example below).
In your example you basically probe, if it is ok to access elements of an empty array. This is of course not legal, since there are none. However you can do:
int[][] array = new int[0][1];
System.out.println(array.length);
With reference to my own example above, a more useful case is:
int[][] array1 = new int[1][1];
int[][] array2 = new int[0][1];
array1[0][0] = 1;
int [][] concat = Stream
.concat(Arrays.stream(array1), Arrays.stream(array2))
.toArray(int[][]::new);
System.out.println(Arrays.deepToString(concat));
Thus empty arrays allow to for "good" code, without ifs to exclude, illegal cases, which actually are totally fine.
as per your declaration:
int[][] array = new int[0][1];
you have declared 2D array where length of the array is 0
it means it will not be able to contain any element thats why
System.out.println(array[0][0]). array[0][0] is out of bound index error
An array dimension of zero means the array has zero elements. Hence there is no element at index 0 (zero).
When you declare a two-dimensional array in Java, the first array dimension is mandatory.
Refer to chapter 10 of the Java Language Specification.
I am new to Java and Here is my code.
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
String[] onedata={"j","k","l"};
the thing I want to do here is that, I want to append the onedata into datas at last index value.
Please help let me know that how can I do this.
You can use an ArrayList because their sizes are mutable. For example:
String[][] datas={{"a","b","c"},{"d","e","f"},{"g","h","i"}};
List<String[]> datasList = new ArrayList<>(Arrays.asList(datas));
String[] onedata = {"j","k","l"};
datasList.add(onedata);
datas = datasList.toArray(new String[datasList.size()][]);
The things you are dealing with are arrays (String[]) and multidimensional arrays (String[][]) in Java, not lists. Their length is fixed. Therefore to append a new item to an array in such way that the length increases (so not by replacing the last item in the current array) you would need to create a new array with length n+1, assign the old values to the first n indices and then the new value to the index n+1.
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);
}
Ok, so I have a 2D array that returns an array.
Object[][] sample = new Object[1][1];
//ok just imagine sample already has an array inside of it
How do I retrive the array within the 2d array?
I have tried to create a new array with the value,
object[] = sample[0][0];
but it just creates an error.
When I print the value of
sample[0][0]
it returns the value:
[[Ljava.lang.Object;#4e25154f
I do not know how to solve this.
sample[0][0] is Object not int[], sample[0] can be one dimensional array or any Object, note that arrays are also Object in java.
To print multidimensional array you can use Arrays.deepToString(twoDarray) but this does not work if you have stored specifically Object.
Moreover, [[Ljava.lang.Object;#4e25154f is the result of default toString representation of the Object stored at sample[0][0] which is I think an array. To print array you can use Arrays.toString(int[]).
I guess this is what you are trying to do,
Object[][] obj = new Object[1][1];
obj[0][0] = new int[]{0,1,0,2};
System.out.println(obj);
//To get int[]
int[] arr= (int[]) obj[0][0];//Need to cast to the int[] specifically
//because it's currently stored as an Object
System.out.println(Arrays.toString(arr));
OUTPUT
[[Ljava.lang.Object;#1db9742
[0, 1, 0, 2]
sample[0][0] returns the object not int. First you need to downcast it and then retrieve integer value
For example :-
CustomObject co = (CustomObject)sample[0][0]; // downcast here
then retrieve the required field from your custom object
Write a method that will search an array of strings for all strings that contain another string, ignoring capitalization. Then return an array of the found strings.
The method takes two parameters, the query string and the array of strings to search, and returns an array.
If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".
Example: If the string to search for is "me", and the array to search is ["home", "milk", "Mercury", "fish"], the method should return ["home", "Mercury"].
That's my solution and it works in Eclipse, but in a game they display an error message:
array lengths differed, expected.length=1 actual.length=0
Code:
static String[] findWord(String x, String[] y){
ArrayList<String> arrList = new ArrayList<String>();
for(String s: y){
if(s.toLowerCase().contains(x.toLowerCase()))
arrList.add(s);
}
String[] arr = arrList.toArray(new String[arrList.size()]);
if(!arrList.isEmpty())
return arr;
else
return new String[0];
}
I don't know what it means, I try to find it on Google but i can't find something useful for me.
array lengths differed, expected.length=1 actual.length=0
This means you're returning an array of length 0 when the correct return value is an array of length 1. The expected length is 1, and the length you actually returned is 0.
When do you return an array of length 0? It must be the last line of your function that's at fault since that's the only place you return an empty array.
Your code is failing this condition:
If the string isn't contained in any of the strings in the array, the method returns an array containing a single string: "Empty".
When there's no match you're returning new String[0]. You need to return a 1-element array containing the string "Empty".