GeeCON Prague 2014*
The moose likes Java in General and the fly likes need help in properties file- key value pair Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Java in General
Bookmark "need help in properties file- key value pair" Watch "need help in properties file- key value pair" New topic
Author

need help in properties file- key value pair

lokesh jain
Ranch Hand

Joined: Feb 21, 2009
Posts: 58
Hi, I am a newbie in properties files. I am using a property file in which we have key-value pairs. I need to extract the keys in ascending order, however when I use this code
then it gives me the result in descending order, can you please help me getting the keys in ascending order.

Thanks in advance,
Lokesh
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Properties is a subclass of Hashtable<Object,Object> (why Object is used beats me, but ok), so the order is based on hash code, not the real order from the file.

Now, if you need alphabetical order, copy the contents to a TreeSet<String,String>. If you need the order from the properties file, you will need to do custom reading, probably using a LinkedHashMap<String,String>.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42046
    
  64
Properties are a kind of Map (which don't support ordering).

You could subclass the Properties class and add "keyList()" and/or "entryList()" methods to it (which would return an ordered List of what keySet and entrySet would return).

Alternatively, create a SortedMap of the Properties object like "SortedMap sm = new TreeMap(prop)" and iterate over that using entrySet or keySet.

(Edit: too late, I see...)


Ping & DNS - my free Android networking tools app
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Rob:

I think it was for backwards compatibility.

John.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19697
    
  20

Probably so, but a Properties object was never meant to store anything other than String keys and String values. The only reason it was possible to store anything is because Sun decided to make Properties extend Hashtable (it shouldn't have, really).

Sun have made a few more questionable choices like that, like Stack extending Vector.
John de Michele
Rancher

Joined: Mar 09, 2009
Posts: 600
Rob:

I agree. IMHO it would make much more sense just to wrap a HashMap<String, String> object, and add the necessary file and XML functionality.

John.
 
GeeCON Prague 2014
 
subject: need help in properties file- key value pair