1000 Java Tips ebook
Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!.
Q: Why does my Properties object ignore the defaults when I do a get?
JavaFAQ Home » Java IAQ by Peter Norvig
Q: Why does my Properties
object ignore the defaults when I do a get?
You shouldn't do a get on a Properties object; you should do
a getProperty instead. Many people assume that the only
difference is that getProperty has a declared return type of
String, while get is declared to return an Object. But
actually there is a bigger difference: getProperty looks at
the defaults. get is inherited from Hashtable, and it ignores
the default, thereby doing exactly what is documented in the Hashtable
class, but probably not what you expect. Other methods that are
inherited from Hashtable (like isEmpty and toString) will also ignore
defaults. Example code:
Properties defaults = new Properties();
Properties props = new Properties(defaults);
System.out.println(props.get("color") + ", " +
// This prints "null, black"
Is this justified by the documentation? Maybe. The documentation
in Hashtable talks about entries in the table, and the behavior of
Properties is consistent if you assume that defauls are not entries in
the table. If for some reason you thought defaults were entries (as
you might be led to believe by the behavior of getProperty) then you
will be confused.
This tip is reprinted on JavaFAQ.nu by by courtesy of
Peter Norvig I am
thankful for his important contributions to my site - 21 Infrequently Answered
Java Questions. Alexandre Patchine
Printer Friendly Page
Send to a Friend
Search here again if you need more info!