2012-06-01 27 views
0

如果我有代碼看起來像這樣:使用Set來構建集合是否會保留Set屬性? (JAVA)

Collection<Object> c = new HashSet<Object>(); 

將它仍然保留該集合將不能夠包含重複值的屬性。換句話說,在以下情況會發生什麼?

String h = "Hello World!"; 
c.add(h); 
c.add(h); 
+0

是的,你已經構建了一個HashSet。 Collection只是用來描述它的更通用的類型。 –

回答

2

是的,Set的行爲和屬性仍然會成立。 c將只包含的"Hello World!"

public static void main(String[] args) 
{ 
    Collection<Object> c = new HashSet<Object>(); 
    String h = "Hello World!"; 
    c.add(h); 
    c.add(h); 
    System.out.println("c contains " + c.size() + " item(s): " + c); 
    System.out.println("c is an instance of " + c.getClass()); 
} 

以上main方法輸出一個實例:

c contains 1 item(s): [Hello World!] 
c is an instance of class java.util.HashSet 
2

你不是 「構建集」;你只是創建一個新的參考。所以是的,所有的基礎屬性仍然存在,因爲它仍然是你所調用的原始對象的方法。

1

簡而言之:是 - 即使引用變量類型是超類型的HashSet,它仍然是HashSet的對象。

0
String h = "Hello World!"; 
c.add(h);//Returns true 
c.add(h);//Returns false since duplicate elements are not allowed in HashSet 

So only one instance of h will be added to HashSet 
1
HashSet<T> theSet = new HashSet<T>(); 
Collection<T> collection = theSet; 
Iterable<T> iterable = theSet; 
Object object = theSet; 

所有這四個變量是不同類型的(所有的人都必須由頭超類型的HashSet),但它們都指向同一個對象,其類型爲HashSet。無論用什麼變量來訪問對象,它總是以相同的方式運行。這是的主要功能之一。

唯一的區別是你移動繼承樹越高(向上意味着更普通的類型),你就可以訪問更少的方法和字段。所以,你不能調用方法,如object.iterator()iterable.size()等等,但是當你調用常用的方法對所有的變量,它的行爲始終以同樣的方式:

theSet.toString(); // produces [] 
collection.toString(); // produces [] 
iterable.toString() // produces [] 
object.toString(); // produces []