Reputation: 1189
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
Upvotes: 3
Views: 1204
Reputation: 115398
You can either cast your object to array type as mentioned by @Rohit Jain (+1) or use java.util.Array
class that has methods like getLength(obj)
, set(obj, elem, index)
etc, so you can work with dynamically created arrays when array type is defined at runtime.
Upvotes: 4
Reputation: 846
To create an array:
int[] arrayName = new int[%size in int%];
To initialize directly:
int[] arrayName = {1,2,3,4,5};
I don't really get what you want to do, but you can just cast when you need it?
Upvotes: 1
Reputation: 331
@rohit-jain already gave you the solution... Be aware that you're not using the parentheses like he told you to do.
int[] intArray = new int[2];
Object ob = intArray;
((int[])ob)[0]= 5;
System.out.println(intArray[0]);
The output will be "5".
Upvotes: 0
Reputation: 37526
(int[])ob[0] = 5;
Is not actually necessary.
ob[0] = 5
will be compiled to this:
ob[0] = new java.lang.Integer(5);
The problem is that because ob
is an Object array, not an Integer or int array, you won't be able to do math operations without casting.
This feature is called autoboxing. It was created to get around the fact that Java has primitive data types that cannot be used as objects directly. In .NET, Ruby and most other "purer" object oriented platforms you could do something like this:
int x = 5; String valAsString = x.toString();
In Java you'd have to wrap x in an Integer
to do that.
Upvotes: 1
Reputation: 213401
You are trying to cast the value of ob[0]
and not ob
itself. You need to cast your ob
first to int[]
and then use it on index [0]
.
((int[])ob)[0] = 5;
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.
Object ob = new int[5];
int[] tempArr = (int [])ob;
for (int i = 0; i < tempArr.length; i++) {
tempArr[i] = i;
}
Upvotes: 11