Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do we need Properties class in java?

Tags:

java

I have always wondered why I need a Properties class as I can always create a HashMap and keep the key/value pairs there. May be it reduces the amount of code to write to load/store properties file. Because otherwise we have to create BufferedReader and read files and split the String and all these. But if we are going to get our key / value pairs from sources other than file then probably it doesn't make any difference whether we are using Properties class or HashMap class. I just need confirmation whether my thinking process is correct.

Thanks

like image 983
user1539343 Avatar asked May 05 '16 22:05

user1539343


1 Answers

Properties is a class that has been part of Java since Java 1.0 .... well before Map and HashMap were introduced. In fact, you will see that Properties extends the old (legacy) Hashtable class which was the precursor to HashMap.

Properties plays an important role in a significant percentage of Java applications in the form of the system properties object. It cannot be replaced in that role without introducing compatibility problems. (Even a change that introduced a second (dual) properties mechanism would be problematic ... since some code writes to the system Properties object.)

Properties has some important functionality that HashMap does not provide; i.e. the ability to load and save the properties in 2 standard human readable formats.


May be it reduces the amount of code to write to load/store properties file. Because otherwise we have to create BufferedReader and read files and split the String and all these.

Yes. And you will find that the properties file syntax is more complicated than can be parsed with split or regexes. Look at the syntax described here:

  • https://docs.oracle.com/javase/8/docs/api/java/util/Properties.html#load-java.io.Reader-

But if we are going to get our key / value pairs from sources other than file then probably it doesn't make any difference whether we are using Properties class or HashMap class.

Again, correct. For that use-case, HashMap might even be superior. Most methods of Properties / Hashtable are synchronized. If you don't need that synchronization, it is a (small) performance penalty.

like image 126
Stephen C Avatar answered Oct 14 '22 21:10

Stephen C