glm*_*ndr 2566
您可以使用数组声明或数组文字(但只有在声明并立即影响变量时,才能使用数组文字重新分配数组).
对于原始类型:
int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
例如,对于类,String
它是相同的:
String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
Run Code Online (Sandbox Code Playgroud)
当您首先声明数组然后初始化它时,第三种初始化方法很有用.演员是必要的.
String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
Run Code Online (Sandbox Code Playgroud)
小智 263
有两种类型的数组.
默认值的语法:
int[] num = new int[5];
Run Code Online (Sandbox Code Playgroud)
或者(不太喜欢)
int num[] = new int[5];
Run Code Online (Sandbox Code Playgroud)
给定值的语法(变量/字段初始化):
int[] num = {1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)
或者(不太喜欢)
int num[] = {1, 2, 3, 4, 5};
Run Code Online (Sandbox Code Playgroud)
注意:为了方便int [] num更可取,因为它清楚地告诉你这里是关于数组的.否则没什么区别.一点也不.
int[][] num = new int[5][2];
Run Code Online (Sandbox Code Playgroud)
要么
int num[][] = new int[5][2];
Run Code Online (Sandbox Code Playgroud)
要么
int[] num[] = new int[5][2];
Run Code Online (Sandbox Code Playgroud)
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;
Run Code Online (Sandbox Code Playgroud)
要么
int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
Run Code Online (Sandbox Code Playgroud)
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];
Run Code Online (Sandbox Code Playgroud)
所以我们在这里明确定义列.
其他方式:
int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
Run Code Online (Sandbox Code Playgroud)
for (int i=0; i<(num.length); i++ ) {
for (int j=0;j<num[i].length;j++)
System.out.println(num[i][j]);
}
Run Code Online (Sandbox Code Playgroud)
或者:
for (int[] a : num) {
for (int i : a) {
System.out.println(i);
}
}
Run Code Online (Sandbox Code Playgroud)
Ragged数组是多维数组.
有关解释,请参阅官方java教程中的多维数组详细信息
Nat*_*ate 123
Type[] variableName = new Type[capacity];
Type[] variableName = {comma-delimited values};
Type variableName[] = new Type[capacity];
Type variableName[] = {comma-delimited values};
Run Code Online (Sandbox Code Playgroud)
也是有效的,但我更喜欢类型之后的括号,因为更容易看到变量的类型实际上是一个数组.
Ani*_*udh 37
您可以通过多种方式在Java中声明数组:
float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
Run Code Online (Sandbox Code Playgroud)
小智 28
以下显示了数组的声明,但未初始化该数组:
int[] myIntArray = new int[3];
Run Code Online (Sandbox Code Playgroud)
以下显示了数组的声明和初始化:
int[] myIntArray = {1,2,3};
Run Code Online (Sandbox Code Playgroud)
现在,以下还显示了数组的声明和初始化:
int[] myIntArray = new int[]{1,2,3};
Run Code Online (Sandbox Code Playgroud)
但是第三个显示了匿名数组对象创建的属性,它由引用变量"myIntArray"指向,所以如果我们只编写"new int [] {1,2,3};" 那么这就是如何创建匿名数组对象.
如果我们只写:
int[] myIntArray;
Run Code Online (Sandbox Code Playgroud)
这不是数组的声明,但以下语句使上述声明完成:
myIntArray=new int[3];
Run Code Online (Sandbox Code Playgroud)
Che*_*het 27
如果您了解每个部分我觉得很有帮助:
Type[] name = new Type[5];
Run Code Online (Sandbox Code Playgroud)
Type[]
是名为name 的变量的类型("name"称为标识符).文字"Type"是基本类型,括号表示这是该基数的数组类型.数组类型依次是它们自己的类型,它允许您创建多维数组(类型为Type []).该关键字表示为新阵列分配内存.括号之间的数字表示新数组的大小和分配的内存量.例如,如果Java知道基类型需要32个字节,并且您需要大小为5的数组,则需要在内部分配32*5 = 160个字节.Type[][]
new
Type
您还可以使用已存在的值创建数组,例如
int[] name = {1, 2, 3, 4, 5};
Run Code Online (Sandbox Code Playgroud)
它不仅会创建空白空间,还会使用这些值填充它.Java可以告诉原语是整数,并且它们中有5个,因此可以隐式确定数组的大小.
Tho*_*ens 25
或者,
// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
Run Code Online (Sandbox Code Playgroud)
这声明了一个名为arrayName
10 的数组(你要使用0到9的元素).
Dav*_*ave 25
此外,如果您想要更动态的东西,还有List接口.这不会表现得那么好,但更灵活:
List<String> listOfString = new ArrayList<String>();
listOfString.add("foo");
listOfString.add("bar");
String value = listOfString.get(0);
assertEquals( value, "foo" );
Run Code Online (Sandbox Code Playgroud)
小智 14
制作数组有两种主要方法:
这一个,对于一个空数组:
int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
Run Code Online (Sandbox Code Playgroud)
而这一个,对于一个初始化的数组:
int[] array = {1,2,3,4 ...};
Run Code Online (Sandbox Code Playgroud)
您还可以创建多维数组,如下所示:
int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
Run Code Online (Sandbox Code Playgroud)
Hyp*_*ino 10
以原始类型int
为例.声明和int
数组有几种方法:
int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
Run Code Online (Sandbox Code Playgroud)
在所有这些中,您可以使用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};
Run Code Online (Sandbox Code Playgroud)
在方法内部,varargs
被视为正常int[]
.Type...
只能在方法参数中使用,所以int... i = new int[] {}
不会编译.
请注意,在传递int[]
给方法(或任何其他方法Type[]
)时,您不能使用第三种方式.在语句中int[] i = *{a, b, c, d, etc}*
,编译器假定{...}
意味着一个int[]
.但那是因为你要声明一个变量.将数组传递给方法时,声明必须为new Type[capacity]
或new Type[] {...}
.
多维数组很难处理.实质上,2D数组是一个数组数组.int[][]
表示一个int[]
s 数组.关键是如果a 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]
Run Code Online (Sandbox Code Playgroud)
Dmi*_*ets 10
int[] nums1; // best practice
int []nums2;
int nums3[];
Run Code Online (Sandbox Code Playgroud)
int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
Run Code Online (Sandbox Code Playgroud)
int[] nums = new int[3]; // [0, 0, 0]
Object[] objects = new Object[3]; // [null, null, null]
Run Code Online (Sandbox Code Playgroud)
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()};
Run Code Online (Sandbox Code Playgroud)
for
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
}
Run Code Online (Sandbox Code Playgroud)
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
}
Run Code Online (Sandbox Code Playgroud)
Stream
(自 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);
Run Code Online (Sandbox Code Playgroud)
Random
and Stream
(自 Java 8 起)int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
Run Code Online (Sandbox Code Playgroud)
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]]
Run Code Online (Sandbox Code Playgroud)
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()}
};
Run Code Online (Sandbox Code Playgroud)
for
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
}
}
Run Code Online (Sandbox Code Playgroud)
如果你想使用反射创建数组,那么你可以这样做:
int size = 3;
int[] intArray = (int[]) Array.newInstance(int.class, size );
Run Code Online (Sandbox Code Playgroud)
使用不同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]
Run Code Online (Sandbox Code Playgroud)
使用局部变量类型推断:
var letters = new String[]{"A", "B", "C"};
Run Code Online (Sandbox Code Playgroud)
声明一组对象引用:
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
}
}
Run Code Online (Sandbox Code Playgroud)
数组是项目的顺序列表
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 }
};
Run Code Online (Sandbox Code Playgroud)
如果它是一个对象,那么它是相同的概念
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() }
};
Run Code Online (Sandbox Code Playgroud)
在对象的情况下,您需要将其分配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) };
Run Code Online (Sandbox Code Playgroud)
通常,您可以创建M
维度的数组
int [][]..[] array =
// ^ M times [] brackets
{{..{
// ^ M times { bracket
// this is array[0][0]..[0]
// ^ M times [0]
}}..}
// ^ M times } bracket
;
Run Code Online (Sandbox Code Playgroud)
值得注意的M
是,就空间而言,创建维数阵列是昂贵的.因为当你在所有维度上创建一个M
维数组时N
,数组的总大小大于N^M
,因为每个数组都有一个引用,并且在M维度上有一个(M-1)维引用数组.总大小如下
Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
// ^ ^ array reference
// ^ actual data
Run Code Online (Sandbox Code Playgroud)
在Java 8中,您可以像这样使用.
String[] strs = IntStream.range(0, 15) // 15 is the size
.mapToObj(i -> Integer.toString(i))
.toArray(String[]::new);
Run Code Online (Sandbox Code Playgroud)
要创建类对象的数组,您可以使用java.util.ArrayList
.定义一个数组:
public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
Run Code Online (Sandbox Code Playgroud)
为数组指定值:
arrayName.add(new ClassName(class parameters go here);
Run Code Online (Sandbox Code Playgroud)
从数组中读取:
ClassName variableName = arrayName.get(index);
Run Code Online (Sandbox Code Playgroud)
注意:
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
Run Code Online (Sandbox Code Playgroud)
for循环允许你编辑arrayName
(传统的循环):
for (int i = 0; i < arrayName.size(); i++){
//manipulate array here
}
Run Code Online (Sandbox Code Playgroud)
为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]
Run Code Online (Sandbox Code Playgroud)
为[-50,50]之间的整数和双精度[0,1E17]创建一个随机数组:
int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();
Run Code Online (Sandbox Code Playgroud)
2的幂次幂:
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]
Run Code Online (Sandbox Code Playgroud)
对于String [],您必须指定一个构造函数:
String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));
Run Code Online (Sandbox Code Playgroud)
多维数组:
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]]
Run Code Online (Sandbox Code Playgroud)
如果您所说的“数组”是指使用java.util.Arrays
,则可以这样做:
List<String> number = Arrays.asList("1", "2", "3");
Out: ["1", "2", "3"]
Run Code Online (Sandbox Code Playgroud)
这个非常简单明了。
这里有很多答案。我添加了一些棘手的方法来创建数组(从考试的角度来看,了解这一点是件好事)
声明并定义一个数组
int intArray[] = new int[3];
Run Code Online (Sandbox Code Playgroud)
这将创建一个长度为 3 的数组。由于它包含基本类型 int,因此默认情况下所有值都设置为 0。例如,
intArray[2]; // Will return 0
Run Code Online (Sandbox Code Playgroud)在变量名前使用方括号 []
int[] intArray = new int[3];
intArray[0] = 1; // Array content is now {1, 0, 0}
Run Code Online (Sandbox Code Playgroud)初始化并向数组提供数据
int[] intArray = new int[]{1, 2, 3};
Run Code Online (Sandbox Code Playgroud)
这次就不需要再提及盒子支架中的尺寸了。即使是一个简单的变体也是:
int[] intArray = {1, 2, 3, 4};
Run Code Online (Sandbox Code Playgroud)长度为0的数组
int[] intArray = new int[0];
int length = intArray.length; // Will return length 0
Run Code Online (Sandbox Code Playgroud)
多维数组类似
int intArray[][] = new int[2][3];
// This will create an array of length 2 and
//each element contains another array of length 3.
// { {0,0,0},{0,0,0} }
int lenght1 = intArray.length; // Will return 2
int length2 = intArray[0].length; // Will return 3
Run Code Online (Sandbox Code Playgroud)在变量前使用方括号:
int[][] intArray = new int[2][3];
Run Code Online (Sandbox Code Playgroud)
如果你在最后放一个方括号就绝对没问题了:
int[] intArray [] = new int[2][4];
int[] intArray[][] = new int[2][3][4]
Run Code Online (Sandbox Code Playgroud)
一些例子
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}}
Run Code Online (Sandbox Code Playgroud)
每个内部元素都具有相同的大小并不是强制性的。
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.
Run Code Online (Sandbox Code Playgroud)
您必须确保如果您使用上述语法,则必须在方括号中指定前进方向的值。否则无法编译。一些例子:
int [][][] intArray = new int[1][][];
int [][][] intArray = new int[1][2][];
int [][][] intArray = new int[1][2][3];
Run Code Online (Sandbox Code Playgroud)
另一个重要特征是协变
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
Run Code Online (Sandbox Code Playgroud)
重要提示:对于引用类型,存储在数组中的默认值为 null。
数组有两种基本类型。
静态数组:固定大小的数组(其大小应在开始时声明,以后不能更改)
动态数组:对此不考虑大小限制。(Java 中不存在纯动态数组。相反,最鼓励使用 List。)
要声明 Integer、string、float 等的静态数组,请使用以下声明和初始化语句。
int[] intArray = new int[10];
String[] intArray = new int[10];
float[] intArray = new int[10];
// Here you have 10 index starting from 0 to 9
Run Code Online (Sandbox Code Playgroud)
要使用动态特性,就必须使用List...List是纯动态Array,不需要在开头声明大小。下面是在 Java 中声明列表的正确方法 -
ArrayList<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
4339746 次 |
最近记录: |