我正在试图反转我的集合,它由两个ArrayList (具有相同的对象)组成。它分别反转两个ArrayList,如下所示:
赛迪
卡尔
赛迪
卡尔
但我想把它们放在一起像:
赛迪
赛迪
卡尔
卡尔
我尝试了两次添加Collections.reverse (就像删除一样),但没有起作用。这是可能的还是我应该放弃?以下是我的当前代码:
List<People> peopleList = new ArrayList<People>();
Student student1 = new Student("Diana", "Carter", new Date("09/15/1992"), 111222333);
peopleList.add(student1);
Faculty faculty1 = new Faculty("Clark", "Kent", new Date("05/22/1990"), 199242003,
323232);
peopleList.add(faculty1);
Staff staff1 = new Staff("Bruce", "Wayne", new Date("01/01/1993"), 161257235,
100000);
peopleList.add(staff1);
Collections.addAll(peopleList);
ArrayList<People> peopleListClone = new ArrayList<People>();
peopleListClone.addAll(peopleList);
peopleListClone.addAll(peopleList);
Collections.addAll(peopleListClone);
DisplayPeople(peopleListClone, "////////////////// People list clone initialized.");
peopleListClone.remove(student1);
peopleListClone.remove(student1);
DisplayPeople(peopleListClone, "////////////////// People list after student elements removed.");
Collections.reverse(peopleListClone);
Collections.reverse(peopleListClone);
DisplayPeople(peopleListClone, "////////////////// People list clone sorted in reverse.");发布于 2016-03-17 04:25:02
尝尝这个。
List<People> peopleListClone = peopleList.stream()
.flatMap(s -> Stream.of(s, s))
.collect(Collectors.toList());而不是
ArrayList<People> peopleListClone = new ArrayList<People>();
peopleListClone.addAll(peopleList);
peopleListClone.addAll(peopleList);发布于 2016-03-17 04:24:48
我仍然不太明白你想用你写出来的代码实现什么。如果这能帮助您理解克隆和逆转ArrayLists的方式,请告诉我。
List<String> list = new ArrayList<String>();
list.add("apple");
list.add("ball");
list.add("cat");
list.add("dog"); // [apple, ball, cat, dog]
Collections.reverse(list);
System.out.println(list); // [dog, cat, ball, apple]
List<String> list2 = new ArrayList<String>();
list2.addAll(list); // MAKING A HARD COPY
Collections.reverse(list2); // REVERSING THE HARD COPY
System.out.println(list2); // [apple, ball, cat, dog] REVERSED HARD COPY
System.out.println(list); // [dog, cat, ball, apple] STILL THE SAME ORIGINALhttps://stackoverflow.com/questions/36051441
复制相似问题