如何声明不同数据类型的数组 [英] How to declare an array of different data types

查看:118
本文介绍了如何声明不同数据类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Java中的数组,我有一个问题。
我知道Java中的数组是类似数据类型的集合,如下所示:

I am working with 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};

以上声明可以读作整数 array是整数类型的集合。

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

考虑一下:

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

在这里,我可以说上面是一个数组,它是一组不相似的数据类型,或者它是一个类似数据类型的 Object 数组,即对象?

Here, can I say that the above is an array which is a collection of dis-similar data types, or is it an Object array of similar data types, i.e. objects?

我对此感到困惑和持怀疑态度。
在Java中,是否可以创建一个可以容纳不同数据类型的数组或任何类型的集合?

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?

推荐答案

Java中的所有对象都扩展了Object。

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];

此代码创建一个长度为6的对象数组。

This code creates an array of objects of length 6.

例如,您可以创建一个数组,其中条目成对出现。在这种情况下,第一个对象是String,第二个是Integer。

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];

这篇关于如何声明不同数据类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆