I have an ArrayList l1 of size N and another l2 of size L < N. I want to put the L first items of l1 to l2. I thought to use the for loop of type for(Object obj : l1) to scan my list of size N and then use l2.add(obj) to add elements on l2, but I am not sure if when I reach the max size of l2 (i.e. L) stops inserting items or continues.
Could somebody suggest me a way to do that? Thanx
Approach: ArrayLists can be joined in Java with the help of Collection. addAll() method. This method is called by the destination ArrayList and the other ArrayList is passed as the parameter to this method. This method appends the second ArrayList to the end of the first ArrayList.
In order to copy elements of ArrayList to another ArrayList, we use the Collections. copy() method. It is used to copy all elements of a collection into another.
We can also change one value of one ArrayList and can look for the same in the other one whether it is changed or not. Syntax : ArrayList<Integer> gfg=new ArrayList<>(); ArrayList<Integer> gfg2=new ArrayList<>(gfg);
To create an ArrayList of specific size, you can pass the size as argument to ArrayList constructor while creating the new ArrayList. Following the syntax to create an ArrayList with specific size. myList = new ArrayList<T>(N); where N is the capacity with which ArrayList is created.
You can use List.subList(int, int)
method to get the first L items
int L = 2;
List<String> newList = new ArrayList<>(inputList.subList(0,L));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With