srk srk - 1 year ago 120
Java Question

How to declare an array of different data types

I am working on arrays in java and I have got a question.
I know that an array in java is a collection of similar data types, as shown below

int[] x = new int[]{1,2,3};

Above declaration can be read as an Integer array which is a collection of integer types.

Consider this

Object[] x = new Object[]{1,2,3,"srk"};

Here, can I say that above is an array which is a collection of dis-similar data types.

It's an Object array of similar data types i.e.., objects.

I am muddled and skeptical about this.
In java, is it possible to create an array or any sort of collection which can hold different data types?

Answer Source

ALL objects in Java extend Object.

Therefore it is possible to be completely non-descriptive when you create the array by declaring it an array of Objects:

Object[] arr = new Object[6];

This code creates an array of objects of length 6.

So for instance, you could create an array where entries come in pairs of two. In this case, the first object is a String and the second is an Integer.

Object[] arr = new Object[6];

arr[0] = new String("First Pair");
arr[1] = new Integer(1);
arr[2] = new String("Second Pair");
arr[3] = new Integer(2);
arr[4] = new String("Third Pair");
arr[5] = new Integer(3);

Now if you want to actually figure out what these objects are then it will require a cast:

int x = (Integer)arr[1];
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download