Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: how to determine type of object in an array of objects?

Tags:

java

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?

like image 555
evilReiko Avatar asked Nov 30 '22 04:11

evilReiko


1 Answers

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.

like image 158
biziclop Avatar answered Dec 15 '22 22:12

biziclop