In: Computer Science
Write a Java program that takes an ArrayList<Integer>, adds k copies of it at the end, and returns the expanded ArrayList. The total size will be (k+1) * n.
public ArrayList<Integer> makeCopies(ArrayList<Integer>, int k) {
}
Example: ArrayList<Integer> has (3,7,4) and k = 2, then the returned, expanded ArrayList will have (3,7,4,3,7,4,3,7,4). The total size is (k+1)*n = (2+1)*3= 9.
public ArrayList<Integer> makeCopies(ArrayList<Integer> list, int k) { ArrayList<Integer> result = new ArrayList<>(list); for (int i = 0; i < k; i++) { result.addAll(list); } return result; }
import java.util.ArrayList; public class ArrayListCopies { public ArrayList<Integer> makeCopies(ArrayList<Integer> list, int k) { ArrayList<Integer> result = new ArrayList<>(list); for (int i = 0; i < k; i++) { result.addAll(list); } return result; } public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(); list.add(3); list.add(7); list.add(4); System.out.println(list); System.out.println(new ArrayListCopies().makeCopies(list, 2)); } }