Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens when there are duplicate keys in Java properties file?

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.

like image 457
aaaidan Avatar asked Sep 24 '12 02:09

aaaidan


2 Answers

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:

  • check to see if the key exists
  • exception thrown based on the presence of the key
  • avoidance of overwriting values
  • out-of-order processing

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.

like image 184
Geoffrey Wiseman Avatar answered Sep 18 '22 11:09

Geoffrey Wiseman


Based on my understanding of Properties, the load method works in a similar fashion to this:

  1. Split the file into lines,
  2. Look at the next line,
  3. Determine the Key-Value pair using some rules (See here)
  4. Put the key value pair into the Properties instance in a fashion similar to the put() method

This 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.

like image 21
Daniel Gratzer Avatar answered Sep 17 '22 11:09

Daniel Gratzer