[英]How to declare and initialize Arrays in java
I am trying to initalize Arrays
using a for-loop.我正在尝试使用 for 循环初始化
Arrays
。 But I can't cast or covert an int
to Arrays
.但我不能将
int
转换或转换为Arrays
。
import java.util.Arrays;
public class InitalizeArrays {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = {1, 2, 5, 8}; //this one is fine
Arrays[] arr2 = new Arrays[5];
for(int i=0; i<=arr2.length; i++)
{
arr2[i]=i; //How to initalize Arrays
System.out.println(arr2[i]);
}
}
}
What am I missing here?我在这里缺少什么?
Arrays
is not an object that you should be using... it is just a set of helper methods for dealing with arrays (note the lower-case "a"). Arrays
不是您应该使用的对象……它只是一组用于处理数组的辅助方法(注意小写的“a”)。 Here's the docs:https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html这是文档:https ://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html
Valid indices of an array are 0
to array.length - 1
(and it's an array of int
s (notArrays
- a utility class). You need to change数组的有效索引是
0
到array.length - 1
(它是一个int
Arrays
(不是Arrays
- 一个实用程序类)。您需要更改
Arrays[] arr2 = new Arrays[5];
for(int i=0; i<=arr2.length; i++)
to something like像
int[] arr2 = new int[5]; // <-- to store an int.
for(int i=0; i<arr.length; i++) // <-- or arr2.length - 1
{
arr2[i]=arr[i]; // <-- to copy arr.
}
or maybe you want to use Arrays.copyOf(int[])
like或者您可能想使用
Arrays.copyOf(int[])
类的
int[] arr2 = Arrays.copyOf(arr, arr.length + 1);
// no for loop to copy needed.
Arrays[] arr2 = new Arrays[5];
should be replaced by应该替换为
int[] arr2 = new int[5];
That's all.就这样。
Sure there won't be any compile time error but there will be runtime error because Java won't treat Arrays[] like int[] arrays.当然不会有任何编译时错误,但会出现运行时错误,因为 Java 不会像对待 int[] 数组那样对待 Arrays[]。 It will be treated as another data type with NO relation to integer arrays.
它将被视为另一种与整数数组没有关系的数据类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.