我正在尝试交换 ArrayList 中的元素,但我不知道如何获取我想要交换的项目的位置,因为它不是二维数组。我正在尝试使用
Collections.swap(list, 3, 3-1);
但是这不起作用。
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 16; i++) {
list.add(i);
}
//System.out.println(list); //[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
Collections.shuffle(list);
// System.out.println(list); //[11, 5, 10, 9, 7, 0, 6, 1, 3, 14, 2, 4, 15, 13, 12, 8]
int[][] a2 = new int[4][4];
for (int i = 0; i < 4; i++) {
for (int j = 0; j< 4; j++) {
a2[i][j] = list.get(i*4 + j);
// System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3, 14, 2, 4], [15, 13, 12, 8]]
}
//System.out.println(Arrays.deepToString(a2)); //[[11, 5, 10, 9], [7, 0, 6, 1], [3, 14, 2, 4], [15, 13, 12, 8]]
// System.out.println();
}
for (int[] row : a2) {
System.out.print("[");
for (int i : row)
System.out.printf("%4d", i);
System.out.println("]");
}
Collections.swap(list, 3, 3-1); //this is where im stuck
}
我将其视为一个矩阵,这就是我想要交换的原因。 ArrayList 中的坐标如何工作?
运行时的输出是:
[ 10 15 12 7]
[ 0 9 2 6]
[ 4 3 1 11]
[ 5 8 14 13]
我想上下和横向交换元素。
最佳答案
我不太确定我理解你的问题,但至于评论:
“我不知道如何获取项目的位置”
使用ArrayList.add(int index, E element)
,这样你就知道刚刚添加的元素位于“index”位置
关于java - 在 ArrayList 中移动元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9467280/