gpt4 book ai didi

java - 拆分和移动数组中的项目

转载 作者:行者123 更新时间:2023-12-01 18:05:46 24 4
gpt4 key购买 nike

我有一个包含整数的数组。

我想要做的是在一个位置分割数组,并将该位置前面的所有项目移动到数组的末尾,并将该位置后面的项目移动到数组的前面。

有人知道如何做到这一点吗?

最佳答案

不要重新发明轮子...

使用List/ArrayList ...它们的存在就是为了让操作变得更加容易......

public static void main(String[] args) {
//define the maze
String[] array = { "A", "B", "C", "D", "1", "2", "3", "4" };
List<String> listA = new ArrayList<>(Arrays.asList(array));
System.out.println(listA);
// this will print [A, B, C, D, 1, 2, 3, 4]

// then add the lower half of the cards maze
List<String> cutList = new ArrayList<>(listA.subList(listA.size() / 2, listA.size()));
System.out.println(cutList);
// this will print [1, 2, 3, 4]

// then add the upper half of the cards maze
cutList.addAll(listA.subList(0, listA.size() / 2));
// this will print [1, 2, 3, 4, A, B, C, D]
System.out.println(cutList);
}

关于java - 拆分和移动数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36526656/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com