Array inside of an Array - Java - 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

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

Expanding Object array to an object 2d array

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

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

How to create an array of objects of a specific class type

I have a function that returns an Object. The Object can contain an array of primatives or an array of objects. In C# I can create an empty array of objects or primatives using code like:
Array values = Array.CreateInstance(/*Type*/type, /*int*/length);
Is there an equivalent in Java?
How to create an array of objects of a specific class type
Test[] tests = new Test[length] ;
And if you want to have a mix up of Primitives and Objects, though it is not suggestable, If you want to mix primitives with Objects
Object[] objs = new Object[length];
That allows you to both primitives(in form of wrappers) and normal Objects together.
If you have a class called Test of your own, you can create an array of Test's like
Note that until you initialise the elements in that array, they have null as their value.
Assuming you only know the element type at execution time, I think you're looking for Array.newInstance.
Object intArray = Array.newInstance(int.class, 10);
Object stringArray = Array.newInstance(String.class, 10);
(That will create an int[] and a String[] respectively.)
Object[] array = new Object[length];
Or with your own type:
MyType[] array = new MyType[length];

Processing language: Get inner array values from ArrayList()

I'm trying to use the ArrayList() method in Processing.
I have this:
ArrayList trackPoints = new ArrayList();
//inside a loop
int[] singlePoint = new int[3];
singlePoint[0] = 5239;
singlePoint[1] = 42314;
singlePoint[2] = 1343;
//inside a loop
trackPoints.add(singlePoint);
So basically I want to add an array "singlePoint" with three values to my ArrayList.
This seems to work fine, because now I can use println(trackPoints.get(5)); and I get this:
[0] = 5239;
[1] = 42314;
[2] = 1343;
However how can I get a single value of this array?
println(trackPoints.get(5)[0]); doesn't work.
I get the following error:
"The type of the expression must be an array type but it resolved to Object"
Any idea what I'm doing wrong? How can I get single values from this arrayList with multiple arrays in it?
Thank you for your help!
Your ArrayList should by typed :
List<int[]> list = new ArrayList<int[]>();
If it's not, then you're using a raw List, which can contain anything. Its get method thus returns Object (which is the root class of all the Java objects), and you must use a cast:
int[] point = (int[]) trackPoints.get(5);
println(point[0]);
You should read about generics, and read the api doc of ArrayList.
The get() method on ArrayList class returns an Object, unless you use it with generics. So basically when you say trackPoints.get(5), what it returns is an Object.
It's same as,
Object obj = list.get(5);
So you can't call obj[0].
To do that, you need to type case it first, like this:
( (int[]) trackPoints.get(5) )[0]

Categories