This is the snippet of code in Java:
Object ob = new int[2];
Now let’s say I want to initialize the array.
This
ob[0] = 5; will not work because ob is of the type of Object.
Casting is not working either:
(int[])ob[0] = 5;
By the way, (int[]ob)[0]= 5;
will cause syntax error.
So, how to assign values at run-time with no hard-coding (e.g. Object ob = new int[]{1,2}?
This is not a home-work, I am trying to understand Java. That is needed in order to prepare for Java certification.
Cheers
You are trying to cast the value of
ob[0]and notobitself. You need to cast yourobfirst toint[]and then use it on index[0].Note: – Parenthesis matters. But why would you like to do something like this?
If you don’t want to hardcode values, and want to take it at runtime, then you should follow something mentioned by @HotLicks in comments.