Page: 2
12. Collections and Generics
Q: 05 Click the Task button. 
Solution: 1. list.add("foo"); ----------- Compilation fails 2. list = new ArrayList<String>(); ------Compilation succeeds 3.list=new ArrayList<Object>( ); ---- Compilation fails 4. String s = list.get(0); ------ Compilation succeeds 5. Object o = list; ----- Compilation succeeds Q: 06 Given: 1. public class Person { 2. private String name; 3. public Person(String name) { this.name = name; } 4. public boolean equals(Person p) { 5. return p.name.equals(this.name); 6. } 7. } Which statement is true? A. The equals method does NOT properly override the Object.equals method. B. Compilation fails because the private attribute p.name cannot be accessed in line 5. C. To work correctly with hash-based data structures, this class must also implement the hashCode method. D. When adding Person objects to a java.util.Set collection, the equals method in line 4 will prevent duplicates. Answer: A Q: 07 Given: 1. import java.util.*; 2. public class Old { 3. public static Object get0(List list) { 4. return list.get(0); 5. } 6. } Which three will compile successfully? (Choose three.) A. Object o = Old.get0(new LinkedList()); B. Object o = Old.get0(new LinkedList<?>()); C. String s = Old.get0(new LinkedList<String>()); D. Object o = Old.get0(new LinkedList<Object>()); E. String s = (String)Old.get0(new LinkedList<String>()); Answer: A, D, E Q: 08 Given: 1. import java.util.*; 2. public class Example { 3. public static void main(String[] args) { 4. // insert code here 5. set.add(new Integer(2)); 6. set.add(new Integer(1)); 7. System.out.println(set); 8. } 9. } Which code, inserted at line 4, guarantees that this program will output [1, 2]? A. Set set = new TreeSet(); B. Set set = new HashSet(); C. Set set = new SortedSet(); D. List set = new SortedList(); E. Set set = new LinkedHashSet(); Answer: A
Page: 2
1
2
3
4
5
6
7
8
9
10
11
12
|