4

Example:

Object[] x = new Object[2];
x[0] = 3; // integer
x[1] = "4"; // String
System.out.println(x[0].getClass().getSimpleName()); // prints "Integer"
System.out.println(x[1].getClass().getSimpleName()); // prints "String"

This makes me wonder: the first object element is an instance of class Integer? or is it a primitive data type int? There is a difference, right?

So if I want to determine the type of first element (is it an integer, double, string, etc), how to do that? Do I use x[0].getClass().isInstance()? (if yes, how?), or do I use something else?

4 Answers 4

6

There is a difference between int and Integer and only an Integer can go into an Object [] but autoboxing/unboxing makes it hard to pin it down.

Once you put your value in the array, it is converted to Integer and its origins are forgotten. Likewise, if you declare an int [] and put an Integer into it, it is converted into an int on the spot and no trace of it ever having been an Integer is preserved.

Sign up to request clarification or add additional context in comments.

Comments

6

not what you asked, but if anyone wants to determine the type of allowed objects in an array:

 Oject[] x = ...; // could be Object[], int[], Integer[], String[], Anything[]

 Class classT = x.getClass().getComponentType(); 

Comments

6

x is an object array - so it can't contain primitives, only objects, and therefore the first element is of type Integer. It becomes an Integer by autoboxing, as @biziclop said

To check the type of a variable, use instanceof:

if (x[0] instanceof Integer) 
   System.out.println(x[0] + " is of type Integer")

Comments

4

You want to use the instanceof operator.

for instance:

if(x[0] instanceof Integer) {
 Integer anInt = (Integer)x[0];
 // do this
} else if(x[0] instanceof String) {
 String aString = (String)x[0];
 //do this
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.