英文:
If a method takes a ragged array, the parameters for that method would be int[][] or int[]?
问题
我刚刚参加了一场考试,教授要求我们编写一个以稀疏数组作为参数的方法。他给出了方法头部如下:
public static int myMethod(int[] myArray)
我有99%的把握认为参数应该是int[][] myArray
,因为这是一个稀疏(二维)数组。
我的教授犯了一个错误吗?还是我理解错了问题?
英文:
I just took a test and the professor asked us to write a method that takes a ragged array as a parameter. He provided the header and it was:
public static int myMethod(int[] myArray)
I am 99% positive that the parameters have to be int[][] myArray
because it is a ragged (2d) array.
Did my professor make a mistake or did I get a question wrong?
答案1
得分: 2
一个不整齐(或锯齿状)的数组是一个包含不同大小数组的数组。如果你谈论的是int
类型,参数类型肯定是int [][]
。
很难确定是谁在这里出了问题,但无论是你还是你的教授肯定漏掉了一些东西 - public static int myMethod(int [] myArray)
绝不会接受一个不整齐的数组。
英文:
A ragged (or jagged) array is an array of arrays of different sizes. If you're talking about int
s, the argument type would definitely be int [][]
.
It's hard to tell who got what wrong here, but either you or your professor definitely missed something - public static int myMethod(int [] myArray)
by no means takes a ragged array.
答案2
得分: 0
自 Java 5 版本开始,您可以在方法签名中使用 varargs。也许您的教授是指的类似于这样的内容。这个方法打印了一种类似于交错的二维数组:
public static int myMethod(int[]... myArray) {
System.out.println(Arrays.deepToString(myArray));
return 0;
}
public static void main(String[] args) {
myMethod(new int[2], new int[]{1, 2, 3}, null);
}
输出结果:
[[0, 0], [1, 2, 3], null]
英文:
Since Java 5 you can use varargs in the method signature. Maybe your professor meant something like this. This method prints a kind of jagged 2d array:
public static int myMethod(int[]... myArray) {
System.out.println(Arrays.deepToString(myArray));
return 0;
}
public static void main(String[] args) {
myMethod(new int[2], new int[]{1, 2, 3}, null);
}
Output:
[[0, 0], [1, 2, 3], null]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论