java - Collections.rotate() 作为 Java 中数组列表的副本
问题描述
ArrayList<Integer> obj = new ArrayList<Integer>(Arrays.asList(1,2,3,4,5));
Collections.rotate(obj,+1);
Collections.rotate(obj,+2);
如果我使用集合旋转arrayList,它会旋转原始数组。我需要旋转特定索引并将其保存在下一个索引/所需索引中而不影响原始索引?
如下所示,都在同一个数组中
input:
1
2
3
4
5
output:
1 5 4
2 1 5
3 2 1
4 3 2
5 4 3
现在我这样做,如下
ArrayList<Integer> arraySec = new ArrayList<Integer>();
ArrayList<Integer> arrayThrd = new ArrayList<Integer>();
arraySec.addAll(obj);
Collections.rotate(arraySec,+1);
arrayThrd.addAll(arraySec);
Collections.rotate(arrayThrd,+1);
因此,对于超过 5 个数组的每个索引,我需要这么多数组。任何其他方式来旋转和返回它的副本而不是原始的
解决方案
如果该Collections.rotate
方法没有返回原始列表的新副本,请自己编写一个!
static <T> ArrayList<T> rotate(ArrayList<T> list, int distance) {
ArrayList<T> newList = new ArrayList<>(list);
Collections.rotate(newList, distance);
return newList;
}
您可以像这样使用它来打印所需的输出:
ArrayList<Integer> obj = new ArrayList<>(Arrays.asList(3,6,4,1,9));
List<ArrayList<Integer>> listOfArrayLists =
IntStream.range(0, obj.size()) // replace obj.size() with however many rotations you want
.mapToObj(x -> rotate(obj, x))
.collect(Collectors.toList());
for (int i = 0 ; i < listOfArrayLists.get(0).size() ; i++) {
for (ArrayList<Integer> listOfArrayList : listOfArrayLists) {
System.out.print(listOfArrayList.get(i));
System.out.print(" ");
}
System.out.println();
}
如果您真的想以这种“转置”方式打印数组列表的所有旋转,那么您实际上并不需要这么多新的数组列表!如果您还没有注意到,输出的第一行与反转并旋转 1 的输入数组列表相同。第二行是反转并旋转 2 的输入,依此类推。因此,这将产生完全相同的结果:
Collections.reverse(obj);
for (int i = 0 ; i < obj.size() ; i++) {
Collections.rotate(obj, 1);
for (Integer j : obj) {
System.out.print(j);
System.out.print(" ");
}
System.out.println();
}
推荐阅读
- c# - 如何在 Listview 中获取选定的 SubItem 索引并突出显示它?
- android - Flutter firebase消息在android上不起作用
- rust - 为具有生命周期的类型实现 Borrow trait
- react-native - React Native Flex框,如何使中间视图占用所有可用空间,给定开始和结束项具有固定宽度
- asp.net-core-3.1 - 将包从“Microsoft.Extensions.Configuration.AzureKeyVault”更改为“Azure.Extensions.AspNetCore.Configuration.Secrets”
- python - DL 的 MFCC 标准化
- javascript - 代码在使用 javascript 的“addEventListener”中不起作用
- c - c语言如何在内存中存储int?
- javascript - Wordpress 在滚动时淡入/淡出(向上和向下)
- windows - 在哪里可以找到适用于 Window 10 的 G++ 最新版本?