Reputation: 33
I wanted to create an array of dynamic types as in javascript. I wanted to convert below code of javascript into java.
const a = [1, [2, 3, [4, 5,[6, 7]....]]]
The above array will have nested array for every 2 elements and depth can be infinite. It is dynamic.
Is there a way to create such array in java? As I found we need to declare before hand the nested arrays as below
List<List<Integer>>
But in above code, I can only use 2 nested list with integers that too I can't use combination of integers and List inside 1st list. If I want to add another list inside second list I need to declare as
List<List<List<Integer>>>
So I need a way to solve this problem
Upvotes: 2
Views: 867
Reputation: 1836
Is there a way to create such array in java?
Yes and no. Java is a strongly typed language. With that said, every object in Java inherits from the built-in class Object
. So you could do something like
Object[] array = new Object[]{1, new Object[]{2, new Object[]{3, /* ... */}}};
Although, using such a construct would be a real pain. You'll need to type-cast values before you can use them as their sourced type again.
Integer a = (Integer) array[0];
Object[] b = (Object[]) array[1];
You can achieve dynamic sizing using List<Object>
.
Upvotes: 3