Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 
Search the JavaFAQ.nu
1000 Java Tips ebook

1000 Java Tips - Click here for the high resolution copy!1000 Java Tips - Click here for the high resolution copy!

Java Screensaver, take it here

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 Go to all tips in Java IAQ by Peter Norvig


Bookmark and Share

Q: Why does my Properties object ignore the defaults when I do a get?

Answer: 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();
defaults.put("color", "black");

Properties props = new Properties(defaults);

System.out.println(props.get("color") + ", " + 
props.getProperty(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  Printer Friendly Page
 Send to a Friend  Send to a Friend

.. Bookmark and Share

Search here again if you need more info!
Custom Search



Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy