如何在Java中声明和初始化数组?
当前回答
声明对象引用数组:
class Animal {}
class Horse extends Animal {
public static void main(String[] args) {
/*
* Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
*/
Animal[] a1 = new Animal[10];
a1[0] = new Animal();
a1[1] = new Horse();
/*
* Array of Animal can hold Animal and Horse and all subtype of Horse
*/
Animal[] a2 = new Horse[10];
a2[0] = new Animal();
a2[1] = new Horse();
/*
* Array of Horse can hold only Horse and its subtype (if any) and not
allowed supertype of Horse nor other subtype of Animal.
*/
Horse[] h1 = new Horse[10];
h1[0] = new Animal(); // Not allowed
h1[1] = new Horse();
/*
* This can not be declared.
*/
Horse[] h2 = new Animal[10]; // Not allowed
}
}
其他回答
以基元类型int为例。有几种方法可以声明和int数组:
int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
在所有这些中,可以使用inti[]而不是int[]i。
对于反射,可以使用(Type[])Array.newInstance(Type.class,capacity);
注意,在方法参数中。。。表示变量参数。本质上,任何数量的参数都可以。用代码更容易解释:
public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
在该方法中,varargs被视为普通的int[]。类型只能在方法参数中使用,因此int.i=newint[]{}不会编译。
请注意,当将int[]传递给方法(或任何其他Type[])时,不能使用第三种方法。在语句int[]i=*{a,b,c,d,etc}*中,编译器假设{…}表示int[]。但这是因为您正在声明一个变量。将数组传递给方法时,声明必须是newType[capartment]或newType[]{…}。
多维数组
多维数组更难处理。本质上,2D阵列是阵列的阵列。int[][]表示int[]的数组。关键是,如果int[][]声明为int[x][y],则最大索引为i[x-1][y-1]。基本上,矩形int[3][5]是:
[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]
或者,
// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
它声明了一个名为arrayName的数组,大小为10(您可以使用元素0到9)。
有多种方法可以在Java中声明数组:
float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
您可以在Sun教程网站和JavaDoc中找到更多信息。
如果要使用反射创建阵列,可以执行以下操作:
int size = 3;
int[] intArray = (int[]) Array.newInstance(int.class, size );
我发现,如果您了解每个部分,这会很有帮助:
Type[] name = new Type[5];
类型[]是名为name的变量的类型(“name”称为标识符)。文字“Type”是基类型,括号表示这是该基的数组类型。数组类型又是它们自己的类型,这允许您创建像类型[][](类型[]的数组类型)这样的多维数组。关键字new表示为新数组分配内存。括号之间的数字表示新阵列的大小以及要分配的内存。例如,如果Java知道基本类型type需要32个字节,并且您需要一个大小为5的数组,那么它需要在内部分配32*5=160个字节。
您还可以使用已经存在的值创建数组,例如
int[] name = {1, 2, 3, 4, 5};
这不仅创建了空白空间,而且用这些值填充了空白空间。Java可以判断基元是整数,并且有5个基元,因此可以隐式地确定数组的大小。
推荐文章
- 在JavaScript中根据键值查找和删除数组中的对象
- 如何格式化Joda-Time DateTime仅为mm/dd/yyyy?
- 如何在POM.xml中引用环境变量?
- 如何在android中复制一个文件?
- 如何确定一个数组是否包含另一个数组的所有元素
- 将整数转换为字符串,以逗号表示千
- 接口方法的最终参数-有什么意义?
- Java中的@UniqueConstraint注释
- 给定一个数字数组,返回所有其他数字的乘积的数组(不除法)
- 多维数组如何在内存中格式化?
- 如何在清洁模式下运行eclipse ?如果我们这样做会发生什么?
- 获取java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory异常
- Java中的正则表达式命名组
- c#和Java的主要区别是什么?
- 什么是NullPointerException,我如何修复它?