首页 > 解决方案 > 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 个数组的每个索引,我需要这么多数组。任何其他方式来旋转和返回它的副本而不是原始的

标签: javaarraylistcollections

解决方案


如果该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();
    }

推荐阅读