Expanding Object array to an object 2d array - java

I am stuck on a problem which requires me to expand an Object array into a 2D Object array. This is the default code they gave me. Does anyone have any clue?
Object[][] expand(Object[] array){
}
The question itself says:
Write a function that takes in an Object[] array, where each value in
array is itself an Object[] and returns an Object[][] with the same
value as the input.
Hint: You will need to do some typecasting/type conversion. You can do
this in one single line.

The Question seems to be clear. You are given a 2d array already but just that the inner array is given in the form of Object class object. Because Object is is parent class for all the classes (even the array is a class internally). You just need to typecast and return the 2d array.
Object[][] expand(Object[] array){
Object[][] result = new Object[array.length][];
for(int i=0;i<array.length;i++){
result[i] = (Object[])array[i];
}
return result;
}

Related

Java Generics : Convert Object Array to Primitive Array based on type

I want to convert an Object array to primitive array based on type of elements present in array.
I want to implement a function which takes Object array and type(as String) as inputs and should return the actual array i.e
func(Object[] arr, String type) should be implemented so that when I call
func(Object[] arr, "int"), it should return int[]
func(Object[] arr, "double"), it should return double[] etc.
Is it possible to do this and if not what can be done to obtain primitive array from Object[] ?
Edit : The use case I have is I need to create 'n' objects of class A which has certain fields(lets say 2). I get fields as Object arrays of length n i.e
Object[] field1
Object[] field2
I also get type of field in String format("int" or "double" etc) which is primitive always. Now can we create objects of class A and if possible how?
Instead of pre-allocating an array, I would suggest using a collection like ArrayList and then generate the resultant array into it.
ArrayList field1Array = Arrays.stream(arr).map(Object::field1)
If there are more fields that need to be allocated, then...
ArrayList field1Array = new ArrayList();
ArrayList field2Array = new ArrayList();
Arrays.stream(arr).forEach(object -> {
field1Array.add(object.getField1());
field2Array.add(object.getField2());
})

Changing the number of dimensions an Java array has

Is there a way of changing the number of dimensions an array has, i.e making this
int[][] i = new int[3][3];
but using it like this
getArray(i); //where getArray only accepts one dimensional arrays
?
You cannot change the number of dimensions in a Java array or array type.
But you can make use of the fact that a Java array is an object ... and subtyping .. and declare a getArray method like this:
Object getArray(Object[], ...) { .... }
You can call this method on a int[][] instance, but a runtime typecast is needed to cast the result to an int[].
For example:
Object getArray(Object[] array, int i) { return array[i]; }
int[][] big = new int[3][3];
int[] slice = (int[]) getArray(big, 0);
On the other hand, if you are really asking about how to flatten a multi-dimensional array into a 1-D array, the getArray method needs to allocate a new array, fill it from the original and return it.
Note you would be returning a brand new array that is unconnected to the original one. And copying an N x N .... x N array is expensive.
For more details: Flatten nested arrays in java
Java is statically-typed language. This means that you cannot change a variable's type at runtime. But in this particular case you can simply use the following invocation:
getArray(i[2]); // put anything between 0 and (outerArrayLength-1) instead of 2 here

print to the console all the items in the ArrayList<String[]>

I have declared an ArrayList of a generic string array
ArrayList<String[]> dataListCol = new ArrayList<String[]>();
I am populating the arraylist this way
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
String[] strArrayCol = new String[2];
strArrayCol[0] = json_data.getString("col1");
strArrayCol[1] = json_data.getString("col2");
dataListCol.add(strArrayCol);
}
I am attempting to print all the individual items in the array as shown
System.out.println("new array " + Arrays.toString(dataListCol.toArray()));
the output is not a meaningful string representation. Please how can I print all the items in the array
As each element itself is an array, you need to call Arrays.toString on each element to print the values, e.g.:
List<String[]> list = new ArrayList<String[]>();
list.stream()
.map(Arrays::toString)
.forEach(System.out::println);
Or, to print just one element, simply use the following inside the loop:
System.out.println(Arrays.toString(strArrayCol));
Update
If you want to assign the String to a reference instead of printing it then you can use Collector, e.g.:
String string = list.stream()
.map(Arrays::toString)
.collect(Collectors.joining("|"));
This will give you pipe separated string for all the elements.
Two way to do that, loop or foreach method.
for (String object: list) {
System.out.println(object);
}
or
ArrayList l=new ArrayList();
l.add(value);
l.forEach((a)->System.out.println(a));
hope that help you
The fact is that you are calling the method tostring() on the array that use the method for generic objects showing to you the hash of that specific object.
You can simply do something like this
int size = t.length;
for (int i=0; i<size; i++) { System.out.println(t[i]);
}
Or in a simpler way you can use
Arrays.toString()
And
System.out.println(Arrays.toString(yourArray));
What's Actually Happening
You've made a list that holds type String[], when you ask the list to return to you it's state represented by an array, the call to toArray(), it returns an array that contains each element in the list.
So the array you've received back is an Object[] that contains all the elements in the list. Remember what type of elements you declared the list to hold -
String[]
Arrays.toString(Object[] array) iterates through the array given calling toString() on each element. The runtime type of each element in the array you gave is String[], therefore on every iteration toString() is being called on an array.
What You Want to Happen
You want to call toString() on each String element in each array of String that the list is holding:
for(String[] strArray : dataListCol) {
System.out.println(Arrays.toString(strArray));
}
or if your a fan of spaghetti output:
System.out.println(Arrays.deepToString(dataListCol.toArray()));
Note Arrays.deepToString(dataListCol.toArray())) does what you wanted. This is because when focusing only on how elements are stored, essentially a List<Object[]> is equivalent to a 2D array, Object[][], just as a List<Object> is equivalent to a single dimension array Object[].
Except elements of an array are stored contiguously in memory whereas Collection classes do not store their elements contiguously (just to keep the memory heroes off my back)

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

Array inside of an Array - Java

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

Categories