gpt4 book ai didi

java - 从给定索引处将 ArrayList 添加到另一个 ArrayList

转载 作者:行者123 更新时间:2023-12-02 06:00:16 24 4
gpt4 key购买 nike

我有两个数组列表

private final ArrayList children = new ArrayList();
private final ArrayList values = new ArrayList();

我有一个方法,当使用值(索引号)调用时,应该填充 children arrayList,从给定索引 i 开始的 values ArrayList 中获取值并填充循环播放。

enter image description here

private void populateList(int i)
{
children.clear();
// A logic to add list in this form as shown in the above picture.
children.add(values.get(i));
children.add(values.get(i + 1));
...
}

我需要一个逻辑,将值 arrayList 中的复制到 arrayList,以从给定索引开始按循环顺序获得最佳性能。

最佳答案

您可以使用简单的 for 循环。在每次迭代中,您都会获取索引 i 处的值,然后递增索引以获得下一个值。

您需要一个循环来迭代正确的次数,并需要模运算符来从 values 列表中获取每个值:

private static void populateList(int i){
children.clear();
for(int p = 0; p < values.size(); p++){
children.add(values.get(i++%values.size()));
}
}

<小时/>或者,您可以使用 values 列表的值填充 children 列表。然后只需调用 Collections.rotate(请注意,列表中的索引是 0 基索引):

private void populateList(int i){
Collections.rotate(children, -i);
}

测试片段:

public class Test { 
private final static ArrayList<Integer> values = new ArrayList<>(Arrays.asList(1,2,3,4,5,6,7,8));
private final static ArrayList<Integer> children = new ArrayList<>();

public static void main (String[] args){
populateList(2); //shift the elements in the list
System.out.println(children);
populateListUsingRotate(-2); //get back the original one
System.out.println(children);
}

private static void populateList(int i){
children.clear();
for(int p = 0; p < values.size(); p++){
children.add(values.get(i++%values.size()));
}
}

private static void populateListUsingRotate(int i){
Collections.rotate(children, -i);
}
}

输出:

[3, 4, 5, 6, 7, 8, 1, 2]
[1, 2, 3, 4, 5, 6, 7, 8]

关于java - 从给定索引处将 ArrayList 添加到另一个 ArrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22730682/

24 4 0