I am trying to copy each element of an ArrayList n times in the same array, that is, I have the following array:
[Hello, World]
And supposing that n is equal to 4 the result would be the following: [Hello, Hello, Hello, Hello, World, World, World, World]
But if n is less than or equal to 0 then I would have to delete the entire contents of the array.
The code I have is the following:
public class Prueba {
public static void main(String[] args) {
String[] ar = {"how", "are", "you?"};
List<String> lista = new ArrayList<>(Arrays.asList(ar));
stutter(lista, 4);
System.out.println(lista);
}
public static void stutter (List<String> list, int k) {
List<String> lista = new ArrayList<>();
if (k <= 0) {
int cont = 0;
while (cont < 2) {
for (int i = 0; i < list.size(); i++) {
list.remove(i);
}
cont++;
}
} else {
for (int i = 0; i < list.size();) {
copiar(lista, k, list.get(i));
}
}
list = lista;
}
public static void copiar(List<String> lista, int k, String s){
int cont = 0;
while (cont < k) {
lista.add(s);
cont++;
}
}
//[how, how, how, how, are, are, are, are, you?, you?, you?, you?]
}
In the stutter method what I do is create a new arraylist and then I check if n is less than or equal to 0 to remove all the contents of the array and if not I use a loop to go through the array and, using the copy method, I copy n times each element of the array into the new array.
Errors in the stutter method:
I add a simpler solution: