ArrayList在已经填充后返回null

时间:2016-04-29 10:12:26

标签: java sorting arraylist

所以我正在玩一个数字排序程序,试图以最有效的方式编写从最低到最高的随机数字列表。

我在运行第一个数字排序方法后遇到问题,传递给第二个方法的ArrayList为空。 我认为这与第一种方法排序技术有关;找到最低值,将其放在一个新的ArrayList中,将其从混合的中删除,然后重新开始。

我不明白的是,我将mixedArray传递给sortingMethod1,这是一个完全不同的类,但不知何故它仍然在主方法中编辑局部变量...请帮忙吗?

P.S。所有这些都使用ArrayLists,即使我引用数组。

主要方法内部:

List<Integer> mixedArray = sorter.generateNumbers(numbers, range);
sorter.printArray(mixedArray); //The Random Numbers
sorter.printArray(sorter.sortingMethod1(mixedArray)); //This prints them out ordered
sorter.printArray(sorter.sortingMethod2(mixedArray)); //This receives a null array

这是sortingMethod1:

public List<Integer> sortingMethod1(List<Integer> mixedArray){  //Finds the lowest, places it into a new array.
    List<Integer> sortedArray = new ArrayList<Integer>();
    while (!mixedArray.isEmpty()) {
        int lowest = mixedArray.get(0);
        for (int i = 1; i < mixedArray.size(); i++) {
            if (mixedArray.get(i) < lowest) {
                lowest = mixedArray.get(i);
            }
        }
        sortedArray.add(lowest);
        mixedArray.remove(mixedArray.indexOf(lowest));
    }
    return sortedArray;

根据要求,sortedMethod2,但它仍然未经测试

 public List<Integer> sortingMethod2 (List<Integer> mixedArray) {   // Finds the lowest, places it at beginning
        for (int i = 0; i < mixedArray.size(); i++) {
            int lowest = mixedArray.get(i);
            for (int x = i; x < mixedArray.size(); x++) {
                if (mixedArray.get(x) < lowest) {lowest = mixedArray.get(x);}
            }
            Collections.swap(mixedArray, i, mixedArray.indexOf(lowest));
        }
        return mixedArray;
    }

0 个答案:

没有答案