如何在Java中声明和初始化数组?
当前回答
int[] x = new int[enter the size of array here];
例子:
int[] x = new int[10];
Or
int[] x = {enter the elements of array here];
例子:
int[] x = {10, 65, 40, 5, 48, 31};
其他回答
要创建类对象的数组,可以使用java.util.ArrayList.来定义数组:
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
为数组赋值:
arrayName.add(new ClassName(class parameters go here);
从阵列中读取:
ClassName variableName = arrayName.get(index);
注:
variableName是对数组的引用,这意味着操纵variableName将操纵arrayName
对于循环:
//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName
for循环,允许您编辑arrayName(常规for循环):
for (int i = 0; i < arrayName.size(); i++){
//manipulate array here
}
int[] x = new int[enter the size of array here];
例子:
int[] x = new int[10];
Or
int[] x = {enter the elements of array here];
例子:
int[] x = {10, 65, 40, 5, 48, 31};
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
也是有效的,但我更喜欢在类型后面加括号,因为更容易看出变量的类型实际上是一个数组。
在Java 9中
使用不同的IntStream.iterate和IntStream.takeWhile方法:
int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();
Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();
Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
在Java 10中
使用局部变量类型推断:
var letters = new String[]{"A", "B", "C"};
声明对象引用数组:
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
}
}
推荐文章
- 在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,我如何修复它?