[Solved] How to repeatedly add the same element to an array [closed]


Based on the example you provided, it seems to me that you want to repeatedly add the same elements (plural) into your array a particular N number of times.

Because arrays are fixed in size, you can’t declare
int[] a1 = {1,2,3};and then attempt to add more elements to it. That is why I recommend you use an ArrayList. Here is an example of how you could create an ArrayList and repeatedly add the same elements to it a set number of times.

    // 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);

You can also create a 2-d ArrayLists and do the same thing by using addAll() to add the pattern of elements an N number of times.

solved How to repeatedly add the same element to an array [closed]