简体   繁体   English

Java-将元素从ArrayList移到数组

[英]Java- Moving elements from a ArrayList to an Array

I currently have a randomly mixed ArrayList . 我目前有一个随机混合的ArrayList

public static void main(String[] args) {
    ArrayList<Integer> solution = new ArrayList<>();
    for (int i = 1; i <= 48; i++) {
        solution.add(i);
    }
    Collections.shuffle(solution);

This gives me a ArrayList with the numbers 1-48 randomly mixed. 这给了我一个1-4随机混合的数字的ArrayList Now I have 4 arrays and I want to randomly add the elements of the ArrayList with out repetition. 现在我有4个数组,我想不加重复地随机添加ArrayList的元素。

 int[] heartsRow = new int[14];
 int[] diamondsRow = new int[14];
 int[] spadesRow = new int[14];
 int[] clubsRow = new int[14]; 

The reason the new arrays contain 14 elements is because the first two elements will always be the same. 新数组包含14个元素的原因是,前两个元素将始终相同。

    heartsRow[0] = 1;
    heartsRow[1] = 0;
    diamondsRow[0] = 14;
    diamondsRow[1] = 0;
    spadesRow[0] = 27;
    spadesRow[1] =0;
    clubsRow[0] = 40;
    clubsRow[1] = 0;

I want to completely fill each array with non-repeating elements of the ArrayList . 我想用ArrayList非重复元素完全填充每个数组。

You could use a counting loop over the list, increment the counter by 4 in each step, and assign elements to the arrays with adjusted offsets: 您可以在列表上使用计数循环,在每个步骤中将计数器增加4,然后将元素分配给具有调整偏移量的数组:

for (int i = 0; i + 3 < solution.size(); i += 4) {
  int j = i / 4;
  heartsRow[2 + j] = solution.get(i);
  diamondsRow[2 + j] = solution.get(i + 1);
  spadesRow[2 + j] = solution.get(i + 2);
  clubsRow[2 + j] = solution.get(i + 3);
}

You can make 4 for loops, from 0 to 11, 12 to 23, 24 to 35 and 36 to 47, and add in your lists. 您可以创建4个for循环,从0到11、12到23、24到35和36到47,然后添加到列表中。

for (int i = 0; i < 12; i++)
    heartsRow[i + 2] = solution.get(i);

for (int i = 0; i < 12; i++)
    diamondsRow[i + 2] = solution.get(i + 12);

for (int i = 0; i < 12; i++)
    spadesRow[i + 2] = solution.get(i + 24);

for (int i = 0; i < 12; i++)
    clubsRow[i + 2] = solution.get(i + 36);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM