I have to write a method that takes arguments List and int n.
Method should multiply content of given List in the same List. If n = 0, than List shoud be empty. If n = 1, List should be the same as before.
For example:
List<Integer> list = Arrays.asList(1,2,3);
multiply(list, 2);
System.out.println(list);
desired output:
[1,2,3,1,2,3]
Method signature can not be changed:
public static void multiply(List<?> list, int n) {
}
I tried this:
public static void multiply(List<?> list, int n) {
List<? super Object> copy = new ArrayList<>();
if (n == 0) {
list.clear();
}
for (int i = 1; i <= n; i++) {
copy.addAll(list);
}
list.clear();
list.addAll(copy); // this is not allowed
}
Thank you for advices!
Aucun commentaire:
Enregistrer un commentaire