【发布时间】:2015-01-07 06:26:43
【问题描述】:
我有一个如下所述的 ArrayList(我的代码片段)。
我的列表元素最初按此顺序排列 - ("Periodic", "Multiple", "Single", "Subsequent", "Consecutive")。
在我的 List 元素上应用 Collections.rotate() 后,修改后的 List 应该看起来像 -
(“周期性”、“后续”、“多个”、“单个”、“连续”)。
元素“Subsequent”需要向后移动到List中的第一个索引元素,即“Multiple”,这样第一个索引的元素在旋转后会被下推到第二个索引。
当我尝试使用 Collections.rotate() 时,它会引发异常。
IllegalArgumentException “fromIndex > toIndex”。
我研究并理解了错误,toIndex应该总是大于或等于fromIndex,但我不知道如何修改我的代码sn-p为了实现我所需要的。
任何建议将不胜感激。
难道不能使用 rotate() 方法在 List 中向后移动元素吗?
List<String> list = new ArrayList<String>(Arrays.asList("Periodic", "Multiple", "Single", "Subsequent", "Consecutive"));
for (int i = 0; i < list.size(); i++) {
int indexOfSubName = 0;
int indexOfMultipleName = 0;
String name = list.get(i);
if (name.equalsIgnoreCase("Subsequent")) {
indexOfSubName = list.indexOf(name);
}
if (name.equalsIgnoreCase("Multiple")) {
int indexOfMultipleName = list.indexOf(name);
}
Collections.rotate(list.subList(indexOfSubName , indexOfMultipleName ), 1);
}
【问题讨论】:
-
你的意思是用第一个元素交换 n-1 吗?
-
很抱歉我已经编辑了我的问题。我不是说将 n-1 与第一个元素交换,我的意思是将 n-1 元素移动到第一个索引位置,以便在旋转后将第一个索引处的元素下推到第二个索引。
标签: java arraylist collections