java - 对数组进行洗牌时遇到问题 - 返回 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
我不确定为什么temp
是null而不是Integer。谁能给我解释一下?我应该如何修改此代码以使其正常工作?
解决方案
Integer[] data = new Integer[size];
是一个整数数组,但直到分配数组中的所有成员为空,您正在打印。首先正确初始化数组:
Integer[] array = new Integer[5];
array[0]= new Integer(0);
array[1]= new Integer(1);
推荐阅读
- javascript - Karma Jasmine 具有可观察的代码覆盖率,但未完全覆盖
- .net - Azure Monitor - REST API 自定义日志 - .Net
- r - 如何在R中将英尺转换为厘米?
- excel - Sum 命名范围由几列和几行组成
- python - 比较 Pandas 列中的重叠
- java - 使用流从地图中填充对象列表
- mysql - 管道 SED 输出到 mysql
- python - 如何在具有新向量的预先计算的矩阵中找到余弦相似度?
- javascript - 对齐 highcharts 的 xAxis
- java - 在 Java 中使用 File.mkdirs 创建文件夹时将模式设置为 777