2013-10-18 61 views
5

我使用從this stackOverflow post的代碼,做什麼,我希望:爲什麼UIManager.getDefaults()的keySet()返回比UIManager.getDefaults不同的值()。鍵()?

Enumeration<Object> keys = UIManager.getDefaults().keys(); 
    while (keys.hasMoreElements()) { 
     Object key = keys.nextElement(); 
     Object value = UIManager.get(key); 
     if (value instanceof FontUIResource) { 
      FontUIResource orig = (FontUIResource) value; 
      Font font = new Font(orig.getFontName(), orig.getStyle(), orig.getSize()); 
      UIManager.put(key, new FontUIResource(font)); 
     } 
    } 

我試圖把它重構爲下面的代碼,它只是通過幾個類javax.swing.plaf中,而不是循環全套組件。我試着圍繞Swift API和HashTable API進行挖掘,但是我覺得我仍然缺少一些明顯的東西。

for(Object key : UIManager.getDefaults().keySet()){ 
     Object value = UIManager.get(key); 
     if(value instanceof FontUIResource){ 
      FontUIResource orig = (FontUIResource) value; 
      Font font = new Font(orig.getFontName(), orig.getStyle(), orig.getSize()); 
      UIManager.put(key, new FontUIResource(font)); 
     } 
    } 

爲什麼第一個代碼塊遍歷和更改所有字體資源,而僅次於遍歷項目屈指可數任何想法?

+1

另見本相關[Q&A](http://stackoverflow.com/q/5729306/230513)。 – trashgod

回答

2

That's一個很好的問題,該方法使用的是回報完全不同的對象回答y。

UIManager.getDefaults()鍵();返回枚舉。枚舉並不擔心重複集合上的對象來迭代。

UIManager.getDefaults()。keySet()返回一組,因此它不能包含repeted對象。當元素將被插入到set時,equals對象的equals方法用於檢查對象是否已經在set上。您正在尋找一種FontUIResource的對象,這個對象有下列實現操作系統的equals方法:

public boolean equals(Object obj) 
    Compares this Font object to the specified Object. 
Overrides: 
    equals in class Object 
Parameters: 
    obj - the Object to compare 
Returns: 
    true if the objects are the same or if the argument is a Font object describing the same font as this object; false otherwise. 

所以在那種FontUIResource與參數的設定所有按鍵描述相同的字體沒有插入其中一個插入的集合。 Consecuently集合只有地圖上的鍵的一個子集。關於Java集上

更多信息:

http://goo.gl/mfUPzp

+0

謝謝,@nrodriguez。我熟悉枚舉和集合之間的區別,但我沒有意識到FontUIResource以這種方式定義了平等! –

相關問題