What is the defined behaviour when there are duplicate keys in a Java .properties
file?
thing.valueA = 1
thing.valueB = 2
thing.valueA = 99
Which value is guaranteed to be used for thing.valueA
? 1, 99, or undefined? Is this behaviour documented anywhere?
NB. I am not asking whether duplicate keys are considered best practice.
Because this isn't defined in the spec for the class, I'd say the most correct answer to this question is that the result is undefined, and could vary from implementation to implementation.
However, because java.util.Properties inherits from java.utils.Hashtable, the most likely implementation is exactly as described by @jozefg, and you can see in the OpenJDK source that the Sun implementation works that way (Properties.java:345 as of the time of this writing). Read each line, parse it to decide if you need to append other lines, separate key and value, put key/value in Hashtable.
There's no:
It's all very simple and basically assumes either that you haven't used duplicate keys, or that if you have, it's your problem to sort out.
Now, of course, to be totally sure you'd want to look at all the likely JVMs or at least the target JVM for your code to make sure the implementation doesn't differ, but I think this implementation is the most likely one.
Based on my understanding of Properties
, the load method works in a similar fashion to this:
put()
methodThis would mean that your example would display 99
.
The load method is basically designed to work as though you had sat down and typed out
propInstance.put("Key", "Value");
propInstance.put("Other", "Thing");
etc etc
To understand this behavior, see the documentation for Hashtable.put()
which specifies that it updates any duplicates with the new value. Since Hashtable is the superclass for Properties, Properties also replicates this behaviour.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With