nerdexam
Oracle

1Z0-819 · Question #91

Given: List<String> hsl = new LinkedList<String>(); Set<String> hs1 = new HashSet<String>(); String[] s = {"a", "b", "c", "b", "a"}; for (String st : s) list1.add(st); hs1.add(st)…

The correct answer is A. 5 5 3 5. Option A (5 5 3 5) is correct because hsl and list1 are the same variable - a classic exam font trick where the lowercase letter l is visually identical to the digit 1. The LinkedList receives all 5 strings (duplicates included), so both hsl.size() and list1.size() return 5…

Working with Arrays and Collections

Question

Given: List<String> hsl = new LinkedList<String>(); Set<String> hs1 = new HashSet<String>(); String[] s = {"a", "b", "c", "b", "a"}; for (String st : s) list1.add(st); hs1.add(st); System.out.print(hsl.size() + " " + list1.size() + " "); HashSet hs2 = new HashSet(list1); LinkedList list2 = new LinkedList(hsl); System.out.print(hs2.size() + " " + list2.size()); What is the result?

Options

  • A5 5 3 5
  • B3 10
  • C3 5
  • D5 5 3 3

How the community answered

(40 responses)
  • A
    85% (34)
  • B
    8% (3)
  • C
    3% (1)
  • D
    5% (2)

Explanation

Option A (5 5 3 5) is correct because hsl and list1 are the same variable - a classic exam font trick where the lowercase letter l is visually identical to the digit 1. The LinkedList receives all 5 strings (duplicates included), so both hsl.size() and list1.size() return 5. When hs2 = new HashSet(list1) is constructed, duplicates ("a" and "b") are eliminated, leaving only 3 unique elements ("a", "b", "c"), so hs2.size() is 3. Finally, list2 = new LinkedList(hsl) copies all 5 elements faithfully since Lists preserve duplicates, so list2.size() is 5, giving the full output 5 5 3 5.

Why distractors fail: B (3 10) invents numbers that don't correspond to any valid interpretation; C (3 5) forgets the first print statement outputs two values before the second print runs; D (5 5 3 3) incorrectly assumes LinkedList(hsl) deduplicates like a Set, but Lists always preserve all elements including duplicates.

Memory tip: Think "Sets shrink, Lists keep" - any time you construct a HashSet from a collection, duplicates vanish; any time you construct a LinkedList from a collection, every element survives. Also watch for l/1 and O/0 variable-name tricks, which are a staple of Java certification exams.

Topics

#LinkedList behavior#HashSet duplicate handling#Collection constructors#Collection size

Community Discussion

No community discussion yet for this question.

Full 1Z0-819 Practice