Java Array with multiple data types

Java is a strongly typed language. In PHP or Javascript, variables don’t have a strict type. However, in Java, every object and primative has a strict type. You can store mutliple types of data in an Array, but you can only get it back as an Object.

You can have an array of Objects:

Object[] objects = new Object[3];
objects[0] = "foo";
objects[1] = 5;

Note that 5 is autoboxed into new Integer(5) which is an object wrapper around the integer 5.

However, if you want to get data out of the array, you can only get it as an Object. The following won’t work:

int i1 = objects[1]; // Won't work.
Integer i2 = objects[2]; // Also won't work.

You have to get it back as an Object:

Object o = objects[0]; // Will work.

However, now you can’t get back the original form. You could try a dangerous cast:

String s = (String) o;

However you don’t know that o is a String.

You can check with instanceof:

String s = null;

if (o instanceof String)
    s = (String) o;

Leave a Comment