【问题标题】:Why are my lists not rotating in Java?为什么我的列表没有在 Java 中轮换?
【发布时间】:2017-08-12 14:24:56
【问题描述】:
    import java.util.*;
public class RotateList {

    public static void main(String[] args)
    {
        List<List<Integer>> copies = new ArrayList<>();
        List<Integer> list = new ArrayList<>(Arrays.asList(1,2,3));
        int size = list.size();
        Set<List<Integer>> set  = new HashSet<>();
        while(size > 0)
        {
            copies.add(list);
            size--;
        }
        size = list.size();
        System.out.println("Copies Before:");
        System.out.println(copies);

        for(int i = 0; i < copies.size();i++)
        {

            Collections.rotate(copies.get(i), i+1);

        }
        System.out.println("Copies after:");
        System.out.println(copies);
        }

}

输出是:

之前的副本:[[1, 2, 3], [1, 2, 3], [1, 2, 3]] 之后的副本:[[1, 2, 3], [1, 2, 3], [1, 2, 3]]

我不知道我哪里出了问题。

【问题讨论】:

  • copies 中的所有元素都是相同的,你怎么知道它们是否被旋转?总旋转为1+2+3=6,它将所有元素带到它们原来的位置。

标签: java arraylist collections set


【解决方案1】:

问题是您要添加相同的列表 3 次。当您旋转其中一个时,您将旋转所有这些。

您必须创建 3 个单独的列表。

List<List<Integer>> copies = new ArrayList<>();

for(int i = 0; i < 3; i++) {
    copies.add(new ArrayList<>(Arrays.asList(1,2,3)));
}

System.out.println("Copies Before:");
System.out.println(copies);

for (int i = 0; i < copies.size(); i++) {
    Collections.rotate(copies.get(i), i + 1);
}

System.out.println("Copies after:");
System.out.println(copies);

输出:

Copies Before:
[[1, 2, 3], [1, 2, 3], [1, 2, 3]]
Copies after:
[[3, 1, 2], [2, 3, 1], [1, 2, 3]]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多