我想ArrayList
通过遍历它并将每个元素复制到新列表中的特定位置来重新排列它。
在这种情况下,我想将一个元素移动到列表的末尾。例如,如果列表是 ABCDE 并且 j == B,那么新列表应该是 ACDEB。
这是我的代码:
private ArrayList<Job> schedule;
private ArrayList<Job> tempSchedule;
...
schedule = input;
tempSchedule = new ArrayList<Job>(schedule.size());
...
private void moveJob(int j) {
for(int i = 0; i < schedule.size(); i++) {
if(i == j) { //move to the end
tempSchedule.set(schedule.size()-1, schedule.get(i));
} else {
if(i > j && i <= schedule.size() -1) { //move one position back
tempSchedule.set(i - 1, schedule.get(i));
} else { //same position
tempSchedule.set(i, schedule.get(i));
}
}
}
schedule = tempSchedule;
u++;
}
现在我得到一个IndexOutOfBoundsException: Index: 0, Size: 0
at tempSchedule.set
我想问题出在这条线上
tempSchedule = new ArrayList<Job>(schedule.size());
还请解释如何制作深拷贝。
编辑:感谢所有答案。我通过简单地删除该项目并在最后添加它来运行它,就像建议的那样。
我想构建一个新列表的原因是因为我可能不得不在某些时候进行更复杂的重新排列。