SCJP題庫第190題
Given:
1. import java.util.*;
2. public class WrappedString{
3. private String s;
4. public WrappedString(String s){this.s = s;}
5. public static void main(String[] args){
6. HashSet<Object> hs = new HashSet<Object>();
7. WrappedString ws1 = new WrappedString("aardvark");
8. WrappedString ws2 = new WrappedString("aardvark");
9. String s1 = new String("aardvark");
10. String s2 = new String("aardvark");
11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);
12. System.out.println(hs.size()); }}
What is the result?
A. 0
B. 1
C. 2
D. 3
E. 4
F. Compilation fails.
G. An exception is thrown at runtime.
Ans: D
解說:
hs物件有3個
ws1、ws2與s1(s2)
s1與s2為String,比較時一樣,所以不會重複加入hs
ws1與ws2因WrappedString類別並未定義hashCode與equals方法,無法比較 (會先比較hashCode()方法傳回的值是否相同,如果相同,則再使用equals()方法比較,如果兩者都相同,則視為相同的物件。)
Comments