[英]How do I make an array parameter in java?
I tried to make a parameter for an array for a method, but it always comes up with an error. 我试图为方法的数组创建一个参数,但是它总是会出错。
public void methodExample1() {
int array1[] = new int[4]
}
public void methodExample(Array array1[]) {
System.out.println(array1[0]);
}
But it always says there's an error in my parameter. 但是它总是说我的参数有错误。 Is there any way to do this?
有什么办法吗?
Try this: 尝试这个:
public void methodExample(int[] array1)
Explanation: The type is the same that you used for declaring a value that will be passed as parameter (for the moment I'm ignoring covariant arrays), for instance if you do this: 说明:类型与您用于声明将作为参数传递的值(目前我忽略协变量数组)的类型相同,例如,如果执行此操作:
int[] array1 = new int[4];
... Then, at the time of passing it as a parameter we'll write it like this: ...然后,在将其作为参数传递时,我们将其编写为:
methodExample(array1)
Also notice that the size of the array must not be passed as parameter, and that by convention the []
part goes right after the type of the array's elements (in fact, int[]
is the type of the array), and not after the array's name. 还要注意,数组的大小一定不能作为参数传递,按照约定,
[]
部分在数组元素的类型之后(实际上, int[]
是数组的类型)之后,而不是数组的名称。
I assume that you are trying to pass array as a parameter to a method , to initialize it and then call another method to print it? 我假设您正在尝试将数组作为参数传递给方法,以对其进行初始化,然后调用另一个方法进行打印?
In java you have to create an object and "allocate" memory space for it by calling to new ... 在Java中,您必须创建一个对象并通过调用new对象为其“分配”内存空间。
so you can do like that : 所以你可以这样:
public static void main(String[] args) {
int [] m_array; // creating a array reference
m_array = new int[5]; // allocate "memory" for each of of them or you can consider it as creating a primitive of int in each cell of the array
method(m_array); // passing by value to the method a reference for the array inside the method
}
public void method(int [] arr) // here you are passing a reference by value for the allocated array
{
System.out.println(arr[0]);
}
If I understand your question, then you could use Array
, and something like 如果我理解您的问题,则可以使用
Array
,例如
public static void methodExample(Object array1) {
int len = Array.getLength(array1);
for (int i = 0; i < len; i++) {
System.out.printf("array1[%d] = %d%n", i, Array.get(array1, i));
}
}
public static void main(String[] args) {
methodExample(new int[] { 1, 2, 3 });
}
Output is 输出是
array1[0] = 1
array1[1] = 2
array1[2] = 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.