Why does UIManager.getDefaults().keySet() return different values than UIManager.getDefaults().keys()?

StackOverflow https://stackoverflow.com/questions/19456693

  •  01-07-2022
  •  | 
  •  

Question

I'm using the code from this stackOverflow post, which does what I expect:

    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));
        }
    }

I tried to refactor it to the following code, which only loops through a couple of classes in javax.swing.plaf instead of the full set of components. I've tried digging around the swing API and HashTable API, but I feel like I'm still missing something obvious.

    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));
        }
    }

Any ideas why the first block of code loops over and changes all font resources, while the second only loops over a handful of items?

Was it helpful?

Solution

That´s a nice question the answer y that the method you are using returns complete different objects.

UIManager.getDefaults().keys(); return a Enumeration. The enumeration is not worried about having repited objects on the collection to iterate.

UIManager.getDefaults().keySet() Returns a Set and therefore it can not contain repeted objects. When elements are going to be inserted on the set que equals method of the object is used to check is the object is allready on the set. You are looking for objects of kind FontUIResource and this objects have a the following implementation os equals method:

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.

So on the set all the keys of kind FontUIResource with an argument describing the same font are not inserted on the set ones one of them is inserted. Consecuently the set has only a subset of the keys on the map.

More info about java sets on :

http://goo.gl/mfUPzp

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top