如果一个方法接受一个不规则数组,那么该方法的参数是int[][]还是int[]?

huangapple go评论70阅读模式
英文:

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 ints, 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]

huangapple
  • 本文由 发表于 2020年9月19日 22:38:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/63969930.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定