如何在Java中声明和初始化数组?
当前回答
这里有很多答案。我添加了一些创建数组的技巧(从考试的角度来看,知道这一点很好)
声明和定义数组intintArray[]=新int[3];这将创建一个长度为3的数组。由于它持有一个基元类型int,所有值默认设置为0。例如intArray[2];//将返回0在变量名称前使用方括号[]int[]intArray=新int[3];intArray[0]=1;//数组内容现在为{1,0,0}初始化并向阵列提供数据int[]intArray=新int[]{1,2,3};这一次,无需在方框括号中提及尺寸。甚至一个简单的变体是:int[]intArray={1,2,3,4};长度为0的数组int[]intArray=新int[0];int length=intArray.length;//将返回长度0类似于多维数组int intArray[][]=新int[2][3];//这将创建一个长度为2的数组//每个元素包含另一个长度为3的数组。// { {0,0,0},{0,0,0} }int lenght1=intArray.length;//将返回2int length2=intArray[0].length;//将返回3
在变量之前使用方括号:
int[][] intArray = new int[2][3];
如果你在最后放一个盒子支架,那是绝对好的:
int[] intArray [] = new int[2][4];
int[] intArray[][] = new int[2][3][4]
一些示例
int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
// All the 3 arrays assignments are valid
// Array looks like {{1,2,3},{4,5,6}}
每个内部元素的大小不一定相同。
int [][] intArray = new int[2][];
intArray[0] = {1,2,3};
intArray[1] = {4,5};
//array looks like {{1,2,3},{4,5}}
int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.
如果使用上述语法,则必须确保向前方向必须在方括号中指定值。否则它将无法编译。一些示例:
int [][][] intArray = new int[1][][];
int [][][] intArray = new int[1][2][];
int [][][] intArray = new int[1][2][3];
另一个重要特征是协变
Number[] numArray = {1,2,3,4}; // java.lang.Number
numArray[0] = new Float(1.5f); // java.lang.Float
numArray[1] = new Integer(1); // java.lang.Integer
// You can store a subclass object in an array that is declared
// to be of the type of its superclass.
// Here 'Number' is the superclass for both Float and Integer.
Number num[] = new Float[5]; // This is also valid
重要信息:对于引用的类型,数组中存储的默认值为空。
其他回答
以基元类型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]
数组是项目的顺序列表
int item = value;
int [] one_dimensional_array = { value, value, value, .., value };
int [][] two_dimensional_array =
{
{ value, value, value, .. value },
{ value, value, value, .. value },
.. .. .. ..
{ value, value, value, .. value }
};
如果它是一个物体,那么它就是同一个概念
Object item = new Object();
Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };
Object [][] two_dimensional_array =
{
{ new Object(), new Object(), .. new Object() },
{ new Object(), new Object(), .. new Object() },
.. .. ..
{ new Object(), new Object(), .. new Object() }
};
对于对象,您需要将其赋值为null,以使用新的Type(..)初始化它们,像String和Integer这样的类是特殊情况,将按如下方式处理
String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };
Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };
通常,您可以创建M维数组
int [][]..[] array =
// ^ M times [] brackets
{{..{
// ^ M times { bracket
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ M times } bracket
;
值得注意的是,从空间角度来看,创建M维阵列是昂贵的。因为当您在所有维度上创建一个N的M维数组时,数组的总大小大于N^M,因为每个数组都有一个引用,并且在M维有一个(M-1)维引用数组。总尺寸如下
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
// ^ ^ array reference
// ^ actual data
下面显示了数组的声明,但未初始化数组:
int[] myIntArray = new int[3];
下面显示了数组的声明和初始化:
int[] myIntArray = {1,2,3};
现在,下面还显示了数组的声明和初始化:
int[] myIntArray = new int[]{1,2,3};
但第三个显示了匿名数组对象创建的属性,该属性由引用变量“myIntArray”指向,因此如果我们只写“newint[]{1,2,3};”,那么这就是如何创建匿名数组对象。
如果我们只写:
int[] myIntArray;
这不是数组的声明,但以下语句使上述声明完成:
myIntArray=new int[3];
您可以使用数组声明或数组文字(但仅当您立即声明并影响变量时,数组文字不能用于重新分配数组)。
对于基本类型:
int[] myIntArray = new int[3]; // each element of the array is initialised to 0
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html
int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort
对于类,例如String,它是相同的:
String[] myStringArray = new String[3]; // each element is initialised to null
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
当您首先声明一个数组,然后初始化它,将一个数组作为函数参数传递,或者返回一个数组时,第三种初始化方法非常有用。需要显式类型。
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
package com.examplehub.basics;
import java.util.Arrays;
public class Array {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
/*
* numbers[0] = 1
* numbers[1] = 2
* numbers[2] = 3
* numbers[3] = 4
* numbers[4] = 5
*/
System.out.println("numbers[0] = " + numbers[0]);
System.out.println("numbers[1] = " + numbers[1]);
System.out.println("numbers[2] = " + numbers[2]);
System.out.println("numbers[3] = " + numbers[3]);
System.out.println("numbers[4] = " + numbers[4]);
/*
* Array index is out of bounds
*/
//System.out.println(numbers[-1]);
//System.out.println(numbers[5]);
/*
* numbers[0] = 1
* numbers[1] = 2
* numbers[2] = 3
* numbers[3] = 4
* numbers[4] = 5
*/
for (int i = 0; i < 5; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
/*
* Length of numbers = 5
*/
System.out.println("length of numbers = " + numbers.length);
/*
* numbers[0] = 1
* numbers[1] = 2
* numbers[2] = 3
* numbers[3] = 4
* numbers[4] = 5
*/
for (int i = 0; i < numbers.length; i++) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
/*
* numbers[4] = 5
* numbers[3] = 4
* numbers[2] = 3
* numbers[1] = 2
* numbers[0] = 1
*/
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.println("numbers[" + i + "] = " + numbers[i]);
}
/*
* 12345
*/
for (int number : numbers) {
System.out.print(number);
}
System.out.println();
/*
* [1, 2, 3, 4, 5]
*/
System.out.println(Arrays.toString(numbers));
String[] company = {"Google", "Facebook", "Amazon", "Microsoft"};
/*
* company[0] = Google
* company[1] = Facebook
* company[2] = Amazon
* company[3] = Microsoft
*/
for (int i = 0; i < company.length; i++) {
System.out.println("company[" + i + "] = " + company[i]);
}
/*
* Google
* Facebook
* Amazon
* Microsoft
*/
for (String c : company) {
System.out.println(c);
}
/*
* [Google, Facebook, Amazon, Microsoft]
*/
System.out.println(Arrays.toString(company));
int[][] twoDimensionalNumbers = {
{1, 2, 3},
{4, 5, 6, 7},
{8, 9},
{10, 11, 12, 13, 14, 15}
};
/*
* total rows = 4
*/
System.out.println("total rows = " + twoDimensionalNumbers.length);
/*
* row 0 length = 3
* row 1 length = 4
* row 2 length = 2
* row 3 length = 6
*/
for (int i = 0; i < twoDimensionalNumbers.length; i++) {
System.out.println("row " + i + " length = " + twoDimensionalNumbers[i].length);
}
/*
* row 0 = 1 2 3
* row 1 = 4 5 6 7
* row 2 = 8 9
* row 3 = 10 11 12 13 14 15
*/
for (int i = 0; i < twoDimensionalNumbers.length; i++) {
System.out.print("row " + i + " = ");
for (int j = 0; j < twoDimensionalNumbers[i].length; j++) {
System.out.print(twoDimensionalNumbers[i][j] + " ");
}
System.out.println();
}
/*
* row 0 = [1, 2, 3]
* row 1 = [4, 5, 6, 7]
* row 2 = [8, 9]
* row 3 = [10, 11, 12, 13, 14, 15]
*/
for (int i = 0; i < twoDimensionalNumbers.length; i++) {
System.out.println("row " + i + " = " + Arrays.toString(twoDimensionalNumbers[i]));
}
/*
* 1 2 3
* 4 5 6 7
* 8 9
* 10 11 12 13 14 15
*/
for (int[] ints : twoDimensionalNumbers) {
for (int num : ints) {
System.out.print(num + " ");
}
System.out.println();
}
/*
* [1, 2, 3]
* [4, 5, 6, 7]
* [8, 9]
* [10, 11, 12, 13, 14, 15]
*/
for (int[] ints : twoDimensionalNumbers) {
System.out.println(Arrays.toString(ints));
}
int length = 5;
int[] array = new int[length];
for (int i = 0; i < 5; i++) {
array[i] = i + 1;
}
/*
* [1, 2, 3, 4, 5]
*/
System.out.println(Arrays.toString(array));
}
}
来源于examplehub/java
推荐文章
- URL从Java中的类路径加载资源
- .toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
- Hibernate中不同的保存方法之间有什么区别?
- Java 8流和数组操作
- 在javascript中从平面数组构建树数组
- Java Regex捕获组
- Openssl不被视为内部或外部命令
- 如何添加自定义方法到Spring Data JPA
- 如何在Ubuntu中设置Java环境路径
- 无法执行dex:在Eclipse中超过GC开销限制
- 有人能解释一下JPA和Hibernate中的mappedBy吗?
- 是什么导致JNI调用变慢?
- Java中的&和&&有什么区别?
- 使用Java的Collections.singletonList()?
- 在bash中传递数组作为参数