数组中的维度总是来自 int 类型。想想吧!
int a = 4;
int b = 5;
Shoe shoe = new Shoe (Color.RED, 42, "Leather");
Hat hat = new Hat (17, Color.Black);
Foo foo = foos[a][b];
Zilch pop = bars[shoe][hat]; // no go
如果你有一个 Foos 的多维数组,第一维是 Foo,第二维是 Foos 数组,第三维是 Foo 数组。唯一的变量类型是底部的那个。
问题更新后编辑:
数组不称为静态或原始数组。它们的大小在初始化时是固定的,它们与原语的共同点是,它们是内置的,在某些情况下被威胁为特殊。它们是 - 与所谓的原始类型相反,它们不是原始类型(例如,它们有专门为它们自己的运算符,如* / -)但同时它们是对象,但未在库中声明。
打电话给他们build in-types。
使用 Bhesh Gurung 的把戏:
Object[] arr = {new Integer[]{}, new String[]{}, new Double[]{}};
是在自找麻烦,而且它不是由每个维度的不同数据类型组成的。让我们从尺寸开始:
// One-dimensional object:
JPanel [] panels = new JPanel [3];
// Two-dimensional object:
JPanel [][] panels = new JPanel [3][10];
底层有 JPanel,下一个维度有一个 JPanel 数组。您可以添加更多维度,并且总是会得到一个额外的 (Array of ...)。
您不能在数组中混合不同的数据类型,例如 int 和 char,或 JPanel 和 JFrame,或 int 和 JButton。仅当您抽象出差异,并将 JComponent 用于 JPanel 和 JFrame 作为公共父级时,但这不适用于内置类型 int、char、boolean 等,因为它们不是对象。
但是你不能用自动装箱,用Integer代替int,用Character代替char,然后用Object作为公共父类吗?是的,你可以,但是你不再使用原语,你在乞求麻烦。
Dan 在谈论不同的事情——在多维数组中使用不同的类型进行索引:
byte b = 120;
short s = 1000;
String o [][] = new String[b][s];
b = 7;
s = 9;
o[b][s] = "foobar";
String foo = o[b][s];
使用 bytes 或 short 没有问题,但不能通过将 Array 声明为 byte 或 short 来限制其大小。在大多数情况下,内置整数类型的边界不适合数据类型(想想每年 365 天),特别是因为所有类型都可能变为负数,所以边界检查是必要的,但不能仅限于编译时间。
但现在麻烦了:
我们可以从一开始就将数组声明为二维:
Object[][] ar2 = {
new Integer [] {4, 5, 6},
new String [] {"me", "and", "you"},
new Character [] {'x', 'y', 'z'}};
这很好用,并且无需强制转换即可立即访问内部数组。但是只有编译器知道,元素是 Object 数组——底层类型被抽象掉了,所以我们可以这样写:
ar2[1][1] = 17; // expected: String
ar2[2][0] = "double you"; // expected: Char
这将完美地编译,但你是在自找麻烦并免费获得一个运行时异常。
这是一个整体的来源:
public class ArrOfMixedArr
{
public static void main (String args[])
{
Object[] arr = {
new Integer [] {1, 2, 3},
new String [] {"you", "and", "me"},
new Character [] {'a', 'b', 'c'}};
show (arr);
byte b = 7;
short s = 9;
String o [][] = new String[200][1000];
o[b][s] = "foobar";
String foo = o[b][s];
Object[][] ar2 = {
new Integer [] {4, 5, 6},
new String [] {"me", "and", "you"},
new Character [] {'x', 'y', 'z'}};
show (ar2);
// exeptions:
ar2[1][1] = 17; // expected: String
ar2[2][0] = "double you"; // expected: Char
}
public static void show (Object[] arr)
{
for (Object o : arr)
{
if (o instanceof Object[])
show ((Object[]) o);
else
System.out.print (o.toString () + "\t");
}
System.out.println ();
}
}
现在有什么解决办法?
如果您的 (int, byte, char, String, JPanel, ...) 的基本类型数组长度相等,那么您就有了类似于隐藏对象、数据库行的东西。改用类:
class Shoe {
byte size;
String manufactor;
java.math.BigDecimal price;
java.awt.Color color;
}
Shoe [] shoes = new Shoe [7];
如果你没有相同大小的不同类型,它们可能是不相关的,不应该放在一个公共容器中。