如何在 Java 中声明和初始化数组?
您可以使用数组声明或数组文字(但仅当您立即声明并影响变量时,数组文字不能用于重新分配数组)。
对于原始类型:
int[] myIntArray = new int[3];
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];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
当您先声明一个数组然后对其进行初始化、将数组作为函数参数传递或返回一个数组时,第三种初始化方式很有用。显式类型是必需的。
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
有两种类型的数组。
一维数组
默认值的语法:
int[] num = new int[5];
或(不太喜欢)
int num[] = new int[5];
给定值的语法(变量/字段初始化):
int[] num = {1,2,3,4,5};
或(不太喜欢)
int num[] = {1, 2, 3, 4, 5};
注意:为方便起见,最好使用 int[] num,因为它清楚地表明您在这里谈论的是数组。否则没有区别。一点也不。
多维数组
宣言
int[][] num = new int[5][2];
或者
int num[][] = new int[5][2];
或者
int[] num[] = new int[5][2];
初始化
num[0][0]=1;
num[0][1]=2;
num[1][0]=1;
num[1][1]=2;
num[2][0]=1;
num[2][1]=2;
num[3][0]=1;
num[3][1]=2;
num[4][0]=1;
num[4][1]=2;
或者
int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
参差不齐的阵列(或非矩形阵列)
int[][] num = new int[5][];
num[0] = new int[1];
num[1] = new int[5];
num[2] = new int[2];
num[3] = new int[3];
所以在这里我们明确定义列。另一种方式:
int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
对于访问:
for (int i=0; i<(num.length); i++ ) {
for (int j=0;j<num[i].length;j++)
System.out.println(num[i][j]);
}
或者:
for (int[] a : num) {
for (int i : a) {
System.out.println(i);
}
}
参差不齐的数组是多维数组。
有关说明,请参阅 the official java tutorials 中的多维数组详细信息
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
也是有效的,但我更喜欢类型后面的括号,因为更容易看出变量的类型实际上是一个数组。
int[] a, b;
与 int a[], b;
不同,如果使用后一种形式很容易犯错误。
在 Java 中可以通过多种方式声明数组:
float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
您可以在 Sun tutorial 网站和 JavaDoc 中找到更多信息。
如果您了解每个部分,我发现它会很有帮助:
Type[] name = new Type[5];
Type[]
是称为名称的变量 的类型(“名称”称为标识符)。文字“Type”是基类型,括号表示这是该基的数组类型。数组类型又是它们自己的类型,它允许您创建像 Type[][]
(Type[] 的数组类型)这样的多维数组。关键字 new
表示为新数组分配内存。括号之间的数字表示新数组有多大以及要分配多少内存。例如,如果 Java 知道基本类型 Type
占用 32 个字节,而您想要一个大小为 5 的数组,则它需要在内部分配 32 * 5 = 160 个字节。
您还可以使用已经存在的值创建数组,例如
int[] name = {1, 2, 3, 4, 5};
这不仅会创建空白空间,还会用这些值填充它。 Java 可以分辨出原语是整数并且它们有 5 个,因此可以隐式确定数组的大小。
int[] name = new int[5]
?
下面展示了一个数组的声明,但是数组没有初始化:
int[] myIntArray = new int[3];
下面显示了数组的声明和初始化:
int[] myIntArray = {1,2,3};
现在,下面还显示了数组的声明和初始化:
int[] myIntArray = new int[]{1,2,3};
但是这第三个显示了匿名数组对象创建的属性,它由引用变量“myIntArray”指向,所以如果我们只写“new int[]{1,2,3};”那么这就是创建匿名数组对象的方式。
如果我们只写:
int[] myIntArray;
这不是数组的声明,但以下语句使上述声明完整:
myIntArray=new int[3];
或者,
// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
这声明了一个名为 arrayName
的大小为 10 的数组(您可以使用 0 到 9 的元素)。
此外,如果您想要更动态的东西,可以使用 List 界面。这不会表现得那么好,但更灵活:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
List
是一个泛型类,它有一个类型作为参数,包含在 <>
中。这很有帮助,因为您只需要定义一次泛型类型,然后就可以将它与多种不同的类型一起使用。如需更详细的说明,请参阅 docs.oracle.com/javase/tutorial/java/generics/types.html
创建数组有两种主要方法:
这个,对于一个空数组:
int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
而这个,对于一个初始化的数组:
int[] array = {1,2,3,4 ...};
您还可以制作多维数组,如下所示:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
以原始类型 int
为例。有几种方法可以声明和int
数组:
int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
在所有这些中,您可以使用 int i[]
而不是 int[] i
。
通过反射,您可以使用 (Type[]) Array.newInstance(Type.class, capacity);
请注意,在方法参数中,...
表示 variable arguments
。本质上,任何数量的参数都可以。用代码更容易解释:
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[]
。 Type...
只能用在方法参数中,所以 int... i = new int[] {}
不会编译。
请注意,将 int[]
传递给方法(或任何其他 Type[]
)时,不能使用第三种方式。在语句 int[] i = *{a, b, c, d, etc}*
中,编译器假定 {...}
表示 int[]
。但那是因为你声明了一个变量。将数组传递给方法时,声明必须是 new Type[capacity]
或 new Type[] {...}
。
多维数组
多维数组更难处理。本质上,二维数组是数组的数组。 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]
在 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 中
使用 Local Variable Type Inference:
var letters = new String[]{"A", "B", "C"};
在 Java 8 中,您可以使用类似的东西。
String[] strs = IntStream.range(0, 15) // 15 is the size
.mapToObj(i -> Integer.toString(i))
.toArray(String[]::new);
如果你想使用反射创建数组,那么你可以这样做:
int size = 3;
int[] intArray = (int[]) Array.newInstance(int.class, size );
如果您所说的“数组”是指使用 java.util.Arrays
,您可以这样做:
List<String> number = Arrays.asList("1", "2", "3");
Out: ["1", "2", "3"]
这个非常简单明了。
声明一个对象引用数组:
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 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
以使用 new 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
为 Java 8 及更高版本声明和初始化。创建一个简单的整数数组:
int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
为 [-50, 50] 之间的整数和双精度 [0, 1E17] 之间的整数创建一个随机数组:
int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();
二次幂序列:
double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]
对于 String[] 你必须指定一个构造函数:
String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));
多维数组:
String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
.toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
要创建类对象数组,您可以使用 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
for 循环:
//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName
允许您编辑 arrayName
的 for 循环(常规 for 循环):
for (int i = 0; i < arrayName.size(); i++){
//manipulate array here
}
另一种声明和初始化 ArrayList 的方法:
private List<String> list = new ArrayList<String>(){{
add("e1");
add("e2");
}};
这里有很多答案。我正在添加一些棘手的方法来创建数组(从考试的角度来看,知道这一点很好)
声明并定义一个数组 int intArray[] = new int[3];这将创建一个长度为 3 的数组。由于它包含一个原始类型 int,因此默认情况下所有值都设置为 0。例如,intArray[2]; // 将返回 0 在变量名之前使用方括号 [] int[] intArray = new int[3];整数数组[0] = 1; // 数组内容现在是 {1, 0, 0} 初始化并向数组提供数据 int[] intArray = new int[]{1, 2, 3};这次无需在方括号中提及尺寸。甚至一个简单的变体是: int[] intArray = {1, 2, 3, 4};长度为 0 的数组 int[] intArray = new int[0]; int 长度 = intArray.length; // 将返回长度 0 与多维数组类似 int intArray[][] = new int[2][3]; // 这将创建一个长度为 2 的数组并且 // 每个元素都包含另一个长度为 3 的数组。 // { {0,0,0},{0,0,0} } int lenght1 = intArray.length; // 将返回 2 int 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
重要提示:对于引用类型,存储在数组中的默认值为 null。
数组有两种基本类型。
静态数组:固定大小的数组(它的大小应该在开始时声明,以后不能更改)
动态数组:对此不考虑大小限制。 (Java 中不存在纯动态数组。相反,最鼓励使用 List。)
要声明整数、字符串、浮点数等的静态数组,请使用以下声明和初始化语句。
int[] intArray = new int[10];字符串[] intArray = new int[10];浮动[] intArray = 新的 int[10]; // 这里有 10 个索引,从 0 到 9
要使用动态特性,必须使用 List... List 是纯动态 Array,无需在开始时声明大小。以下是在 Java 中声明列表的正确方法 -
ArrayList
使用局部变量类型推断,您只需指定一次类型:
var values = new int[] { 1, 2, 3 };
或者
int[] values = { 1, 2, 3 }
var
。
var
openjdk.java.net/jeps/286
数组可以包含原始数据类型以及类的对象,具体取决于数组的定义。在原始数据类型的情况下,实际值存储在连续的内存位置。对于类的对象,实际对象存储在堆段中。
https://media.geeksforgeeks.org/wp-content/uploads/Arrays1.png
一维数组:
一维数组声明的一般形式是
type var-name[];
OR
type[] var-name;
在 Java 中实例化一个数组
var-name = new type [size];
例如,
int intArray[]; // Declaring an array
intArray = new int[20]; // Allocating memory to the array
// The below line is equal to line1 + line2
int[] intArray = new int[20]; // Combining both statements in one
int[] intArray = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Accessing the elements of the specified array
for (int i = 0; i < intArray.length; i++)
System.out.println("Element at index " + i + ": "+ intArray[i]);
int[] x = new int[enter the size of array here];
例子:
int[] x = new int[10];
或者
int[] x = {enter the elements of array here];
例子:
int[] x = {10, 65, 40, 5, 48, 31};
声明数组:int[] arr;
Initialize Array:int[] arr = new int[10];
10 表示数组中允许的元素个数
声明多维数组:int[][] arr;
初始化多维数组:int[][] arr = new int[10][17];
10 行 17 列和 170 个元素,因为 10 乘以 17 是 170。
初始化一个数组意味着指定它的大小。
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));
}
}
另一个完整的电影类示例:
public class A {
public static void main(String[] args) {
class Movie {
String movieName;
String genre;
String movieType;
String year;
String ageRating;
String rating;
public Movie(String [] str)
{
this.movieName = str[0];
this.genre = str[1];
this.movieType = str[2];
this.year = str[3];
this.ageRating = str[4];
this.rating = str[5];
}
}
String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};
Movie mv = new Movie(movieDetailArr);
System.out.println("Movie Name: "+ mv.movieName);
System.out.println("Movie genre: "+ mv.genre);
System.out.println("Movie type: "+ mv.movieType);
System.out.println("Movie year: "+ mv.year);
System.out.println("Movie age : "+ mv.ageRating);
System.out.println("Movie rating: "+ mv.rating);
}
}
有时我用它来初始化字符串数组:
private static final String[] PROPS = "lastStart,storetime,tstore".split(",");
它以更昂贵的初始化为代价减少了引用混乱。
宣言
一维数组
int[] nums1; // best practice
int []nums2;
int nums3[];
多维数组
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
声明和初始化
一维数组
使用默认值
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
使用数组字面量
int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};
Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
带循环
int[] nums = new int[3];
for (int i = 0; i < nums.length; i++) {
nums[i] = i; // can contain any YOUR filling strategy
}
Object[] objects = new Object[3];
for (int i = 0; i < objects.length; i++) {
objects[i] = new Object(); // can contain any YOUR filling strategy
}
使用循环 for 和 Random
int[] nums = new int[10];
Random random = new Random();
for (int i = 0; i < nums.length; i++) {
nums[i] = random.nextInt(10); // random int from 0 to 9
}
使用流(Java 8 起)
int[] nums1 = IntStream.range(0, 3)
.toArray(); // [0, 1, 2]
int[] nums2 = IntStream.rangeClosed(0, 3)
.toArray(); // [0, 1, 2, 3]
int[] nums3 = IntStream.of(10, 11, 12, 13)
.toArray(); // [10, 11, 12, 13]
int[] nums4 = IntStream.of(12, 11, 13, 10)
.sorted()
.toArray(); // [10, 11, 12, 13]
int[] nums5 = IntStream.iterate(0, x -> x <= 3, x -> x + 1)
.toArray(); // [0, 1, 2, 3]
int[] nums6 = IntStream.iterate(0, x -> x + 1)
.takeWhile(x -> x < 3)
.toArray(); // [0, 1, 2]
int size = 3;
Object[] objects1 = IntStream.range(0, size)
.mapToObj(i -> new Object()) // can contain any YOUR filling strategy
.toArray(Object[]::new);
Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy
.limit(size)
.toArray(Object[]::new);
使用随机和流(Java 8 起)
int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
多维数组
有默认值
int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]
使用数组字面量
int[][] nums1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
int[][] nums2 = new int[][]{
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
Object[][] objects1 = {
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()},
{new Object(), new Object(), new Object()}
};
带循环
int[][] nums = new int[3][3];
for (int i = 0; i < nums.length; i++) {
for (int j = 0; j < nums[i].length; i++) {
nums[i][j] = i + j; // can contain any YOUR filling strategy
}
}
Object[][] objects = new Object[3][3];
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < nums[i].length; i++) {
objects[i][j] = new Object(); // can contain any YOUR filling strategy
}
}
声明和初始化数组非常容易。例如,您想将 1、2、3、4 和 5 五个整数元素保存在一个数组中。您可以通过以下方式执行此操作:
一个)
int[] a = new int[5];
或者
b)
int[] a = {1, 2, 3, 4, 5};
所以基本模式是通过方法a)进行初始化和声明是:
datatype[] arrayname = new datatype[requiredarraysize];
datatype
应为小写。
因此,通过方法 a 进行初始化和声明的基本模式是:
如果是字符串数组:
String[] a = {"as", "asd", "ssd"};
如果是字符数组:
char[] a = {'a', 's', 'w'};
对于 float double,数组的格式将与整数相同。
例如:
double[] a = {1.2, 1.3, 12.3};
但是当您通过“方法a”声明和初始化数组时,您将不得不手动或通过循环或其他方式输入值。
但是,当您通过“方法 b”执行此操作时,您不必手动输入值。
return {1,2,3}
给出错误,而return new int[]{1,2,3}
工作正常(当然假设您的函数返回一个整数数组)。