首页 > 解决方案 > 对数组进行洗牌时遇到问题 - 返回 null 而不是随机整数

问题描述

private static <T> void shuffle(T[] array){
    if(array==null || array.length < 2){
        return;
    }

    for(int i=1;i<array.length;i++){
        int a = rng.nextInt(i+1);
        System.out.println(a);
        T temp = array[a];
        System.out.println(temp);
        array[a] = array[i];
        array[i] = temp;
    }
}

static boolean checkSorted(ISort sorter, int size) {
    Integer[] data = new Integer[size];
    shuffle(data);
}

这是打印变量a和时的输出temp

0
null
2
null
0
null
2
null
0
null
4
null
7
null
8
null
6

我不确定为什么tempnull而不是Integer。谁能给我解释一下?我应该如何修改此代码以使其正常工作?

标签: javaarrayssortingrandomshuffle

解决方案


Integer[] data = new Integer[size];是一个整数数组,但直到分配数组中的所有成员为空,您正在打印。首先正确初始化数组:

Integer[] array = new Integer[5];
array[0]= new Integer(0);
array[1]= new Integer(1);

推荐阅读