2

I'm saving several values in a properties file, yet whenever I open the file, the values are not written in the order that I coded.

save.setProperty("SN", "foo");
save.setProperty("ID", "bar");
save.setProperty("TN", "example");
save.setProperty("TC", "generic");
save.setProperty("SW", "incorrect");
save.setProperty("NW", "order");
save.store(new FileOutputStream(file.getAbsolutePath(), null);

This is how the file looks when I open it:

#Sat Jul 13 19:28:59 EDT 2013
ID=bar
SW=incorrect
TC=generic
TN=example
NW=order
SN=foo

As you can see, the order is completely off from the coding. I am curious as to why this happens. It is obviously not sorted alphabetically, and I can't see any other reason why it should happen like this.

Aaron
  • 992
  • 3
  • 15
  • 33

2 Answers2

5

The Properties class extends the Hashtable class.

The iteration order of a hash-based set is undefined.


Incidentally, the fact that Properties extends Hashtable, instead of using Hashtable, is considered one of the many design "mistakes" in the JDK.

For a brief list of other "mistakes", see this answer.

Community
  • 1
  • 1
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

There's a good chance that the properties system is using a backing HashMap of some description. This is so that you can set the same property many times over and it will update the current value. To do this efficiently, a HashMap is required. Because of this, the order is entirely up to the implementation of the HashMap (It's not guaranteed to be alphabetical)

AStupidNoob
  • 1,980
  • 3
  • 23
  • 35