ProgrammingHardProduct-company placement · Java
What is printed?
What is printed?
// Java 10 or later List<Integer> base = new ArrayList<>(List.of(1, 2)); List<Integer> view = Collections.unmodifiableList(base); List<Integer> copy = List.copyOf(base); base.add(3); System.out.print(view.size() + " " + copy.size());
- A. 2 2
- B. 3 3
- C. 3 2
- D. 2 3
Correct answer: C. 3 2
unmodifiableList is a read-only VIEW: it cannot be changed through itself but reflects changes to the underlying list. List.copyOf makes an independent immutable copy, so it stays at 2.
More OOP with C++ and Java questions
- What is printed? java Deque<Integer> d = new ArrayDeque<>(); d.push(1); d.offer(2); d.push(3); d.offerFirst(4); d.add(5)…
- What is printed? java Stack<Integer> st = new Stack<>(); Deque<Integer> dq = new ArrayDeque<>(); for (int i = 1; i <= 3; i++) {…
- What is printed? java TreeMap<Integer, String> m = new TreeMap<>(); for (int k : new int[]{10, 20, 30, 40}) m.put(k, "v" + k)…
- What is printed? java Map<String, Integer> h = new HashMap<>(); h.put(null, 1); h.put(null, 2); System.out.print(h.size() + " " +…
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.put("a", 1); int x = m.getOrDefault("b", 0) + m.get("a"); int y =…
- What is printed? java Map<Character, Integer> f = new TreeMap<>(); for (char c : "banana".toCharArray()) f.merge(c, 1, Integer::sum)…