为什么创建然后单独返回`int [] arrayName = {};`冗余? (JAVA)

时间:2016-08-27 21:15:09

标签: java android

我在以下代码中收到Local variable 'answerArray' is redundant警告:

int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
return answerArray;

完整方法:

public int[] answerArray (int answer) {
    Random randomGenerator = new Random();
    int fakeFirstAnswer = randomGenerator.nextInt(10);
    int fakeSecondAnswer = randomGenerator.nextInt(10);

    int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};
    return answerArray;
}

我尝试过像下面这样的重构,但后来发现expects ;错误。

return int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};

有人可以推荐一种语法吗?我刚刚开始使用Java / Android。

1 个答案:

答案 0 :(得分:0)

在Java中,array variable declarations

int[] answerArray = {answer, fakeFirstAnswer, fakeSecondAnswer};

的简写
int[] answerArray = new int[] {answer, fakeFirstAnswer, fakeSecondAnswer};
//                  ^-- the Java compiler does this

但是,return不是变量声明,需要明确的new int[]语法,如Sotirios指出

return new int[] {answer, fakeFirstAnswer, fakeSecondAnswer};

(在这两种情况下,Java都会自动确定数组的长度。)