How to repeatedly add the same element to an array

时间:2018-03-25 20:30:40

标签: java arrays

How to repeatedly add the same element to an array, I am new beginner in Java, could anyone help me solve this problem

For example,

When N = 1
int[] a1 = {1,2,3}

When N = 2
the result is 
a1 = {1,2,3,1,2,3}

what's about 2-d array?

N is the number of rows
When N = 1
int[][] a1 = {{1,2,3},{4,5,6},{7,8,9}}

When N= 2
a2 = {{1,2,3},{4,5,6},{7,8,9}
      {1,2,3},{4,5,6},{7,8,9}}

1 个答案:

答案 0 :(得分:0)

根据您提供的示例,在我看来,您希望重复将相同的元素 s (复数)添加到您的数组中特定N次。

由于数组的大小是固定的,因此您无法声明 int[] a1 = {1,2,3};然后尝试向其添加更多元素。这就是为什么我建议你使用ArrayList。下面是一个如何创建ArrayList并重复添加相同元素的示例。

    // number of times you want to add elements (1, 2, 3)
    int timesToRepeat = 2;

    // your ArrayList instance
    ArrayList<Integer> a1 = new ArrayList<Integer>();

    // use add() to add the integer elements 1, 2, 3
    a1.add(1);
    a1.add(2);
    a1.add(3);

    // clone a1 so we have a non-changing copy of it when we get to our for loop
    ArrayList<Integer> a1copy = (ArrayList<Integer>) a1.clone();

    // here's where it will take the three elements (1, 2, 3) from a1copy
    // it will repeatedly add them to a1 as many times as you specified
    // you specify this number when setting the int variable timesToRepeat
    for (int i = timesToRepeat; i > 1; --i) {
        a1.addAll(a1copy);

    }

    // print your ArrayList
    System.out.println(a1);

您还可以使用addAll()创建一个二维数组列表并执行相同的操作,以多次添加元素模式。