File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes for-each and Properties Class Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "for-each and Properties Class" Watch "for-each and Properties Class" New topic
Author

for-each and Properties Class

Dennis Putnam
Ranch Hand

Joined: Feb 03, 2012
Posts: 217
I need to process all the keys/values in a Properties class. I cannot seem to figure out the syntax of the for loop. I want the correct syntax to do something like:

I guess I need to somehow convert the list of keys to an array or set? TIA.
William P O'Sullivan
Ranch Hand

Joined: Mar 28, 2012
Posts: 859

There is no "keys"

http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html#propertyNames()

WP
Dennis Putnam
Ranch Hand

Joined: Feb 03, 2012
Posts: 217
I meant keySet. Typo. However, I figured it out.
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3014
    
  10
Unfortunately, the Properties class was made to implement Map<Object, Object> when it clearly should have been Map<String, String>. This was probably because Properties was written long before generics came into the language, and Sun in their infinite wisdom chose to retroactively implement Map<Object, Object> in order to not break backwards compatibility for clients using their Properties in an incredibly stupid way. That is, Properties has always allowed people to put things other than Strings in as either keys or values, if they use put() rather than setProperty(), even though only an insane person would ever do this. Rather than fix this error, Sun chose to continue it. That's why you can't simply use "String key : props.keySet()" as you would expect.

Here's another alternative:
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19693
    
  20

Why not loop over the entry set?
Unfortunately you'll need those casts since somebody thought that Properties should extend Hashtable<Object, Object> instead of Hashtable<String, String>, probably because someone somewhere abused Properties and put something other than Strings in it. It's a rubbish reason. If someone was trying to abuse Properties like that they deserve a compiler error.

Wow, beaten by 3 seconds with an answer that's more or less what I said. Auch. Now I know how Campbell feels all the time


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Mike Simmons
Ranch Hand

Joined: Mar 05, 2008
Posts: 3014
    
  10
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: for-each and Properties Class