Java SE8 Practice Question: ArrayList’s add and subList method
Practice Question, Oracle Certified Associate: Java SE8 Programming (1Z0-808)
Sometimes even the actual function of the easiest of methods (no pun intended) can elude us.
How well do you know the behavior of java.util.ArrayList’s add and subList method?
Q: What will the output be after code execution?
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List s1 = new ArrayList(); s1.add("x"); s1.add("y"); s1.add(1, "z"); List s2 = new ArrayList(s1.subList(2, 2)); s1.addAll(s2); System.out.println(s1); } }
Choose one answer:
- a) [x, z, y]
- b) [x, y, z]
- c) [x, y, z, y]
- d) [x, z, y, z]
- e) None of the above
Click here to view answer
The answer is a).
Why?
List is an Interface that ArrayList have implemented. What add(int index, E element) does, is to insert an element into the given index. The existing element on the given index, along with the concurrent elements, will be pushed one step up.
import java.util.ArrayList; import java.util.List; public class Demo { public static void main(String[] args) { List s1 = new ArrayList(); // [] s1.add("x"); // s1: [x] s1.add("y"); // s1: [x, y] s1.add(1, "z"); // s1: [x, z, y] List s2 = new ArrayList(s1.subList(2, 2)); // s1.sublist(2, 2) is an empty array. s1.addAll(s2); // nothing is added to s1. System.out.println(s1); // [x, z, y] } }
The s1.sublist(2, 2) has no range. It returns an empty array.
The way subList(int fromIndex, int toIndex) works, is by giving it a range. A range from 2 to 2 is an empty range. The difference is 0, so no letters will be added.
For example, a range from 0 to 2 would return x, z from the example above, making it [x, z, y, x, z]. Because we have a range from and included 0, up to but not included 2.
Modify the existing code and take a look!