为方法分配多个变量

时间:2018-02-07 19:32:41

标签: java arrays variable-declaration

我正在尝试将3个整数数组分配给返回一个版本的方法。但是,当我尝试这个时,它表示变量bubbleArray和变量insertionArray尚未初始化。是否有另一种方法来执行此操作并仍保持方法中的相同原始值。

    Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();


    bubbleSort(radioValue,bubbleArray);
    selectionSort(radioValue,selectionArray);
    insertionSort(radioValue,insertionArray);

 public Integer[] numGenerator() {
    Random rn = new Random();
    originalOutput.setText("");
    sortedOutput.setText("");
    referenceArray.clear();

    if (number10Button.isSelected()) {
        for (int i = 0; i < 10; i++) {
            int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
            referenceArray.add(answer);
            originalOutput.append(referenceArray.get(i).toString() + "\n");
        }
    } else if (number100Button.isSelected()) {
        for (int i = 0; i < 100; i++) {
            int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
            referenceArray.add(answer);
            originalOutput.append(referenceArray.get(i).toString() + "\n");

        }
    } else if (number1000Button.isSelected()) {
        for (int i = 0; i < 1000; i++) {
            int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
            referenceArray.add(answer);
            originalOutput.append(referenceArray.get(i).toString() + "\n");

        }
    } else if (number5000Button.isSelected()) {
        for (int i = 0; i < 5000; i++) {
            int answer = rn.nextInt((10000 - (-10000)) + 1) + (-10000);
            referenceArray.add(answer);
            originalOutput.append(referenceArray.get(i).toString() + "\n");

        }
    }

    Integer[] bubbleArray = referenceArray.toArray(new Integer[referenceArray.size()]);
    return bubbleArray;
}

1 个答案:

答案 0 :(得分:1)

您的代码声明了3 Integer[]个变量,并将最后一个变量分配给numGenerator()返回的内容。

Integer[] bubbleArray,insertionArray,selectionArray = numGenerator();

既然您需要三个数组,而不仅仅是指向一个数组的三个变量,您需要对数组进行复制,例如与clone()。如果你不制作副本,你将有一个数组按冒泡排序排序,其他排序方法将尝试对已排序的数组进行排序,这不是你想要的。

Integer[] bubbleArray = numGenerator();
Integer[] insertionArray = bubbleArray.clone();
Integer[] selectionArray = bubbleArray.clone();