14

Just wanted to know. What are the differences between java.util.Properties Vs java.util.HashMap<String, String>? Which is preferable?

Vaandu
  • 4,857
  • 12
  • 49
  • 75

6 Answers6

28

There are different purpose of these two utility class. Map, or in your case, HashMap is general purpose storage object where you have unique key, and values to which they point. HashMap can have any object type as their key and any object type as their values.

java.util.Properties is, however, a special purpose map. It is developed to read/write from/to properties files. It has special methods to do so [see load(..)]. Map does not.

So, you have different situations to use them. Places where you need properties to read, you better go with Properties. And places where you want to have lookup values stored off some logic, you go with HashMap<String, String>.

There is no hard and fast rule, you can use HashMap<String, String> and Properties interchangeably. But as an engineer, use right tool for the task.

Nishant
  • 54,584
  • 13
  • 112
  • 127
16

They are similar, but from a design perspective, the Properties class is considered to be one of the "mistakes" of java, because it is a Hashtable (rather than using a Hashtable). It should have been an interface.

Always use the abstract where possible, so this is preferred:

Map<String, String> stuff = new HashMap<String, String>();

Tend to avoid using Properties unless you have to.

Bohemian
  • 412,405
  • 93
  • 575
  • 722
5

Propeties extends Hashtable, which is synchronized by default. HashMap is not synchronized by default. You're trading built-in thread safety for a slight performance improvement, one that you're likely to be unable to measure.

Properties is an older class from Java 1.0. HashMap is part of Joshua Bloch's newer collections API.

duffymo
  • 305,152
  • 44
  • 369
  • 561
3

You have the modern-day ConcurrentHashMap<String, String> for thread safety. Don't really use Properties unless you are using it to read a .properties file.

adarshr
  • 61,315
  • 23
  • 138
  • 167
1

The Properties class is an extension of Hashtable, basically adding functionality to write + read from a disk in a set format (text value pairs like this):

key1=value1
key2=value2

If you want to store it to disk and use that format then use a Properties, otherwise use a HashMap or Hashtable.

AntonyM
  • 1,602
  • 12
  • 12
0

java.util.Properties is a Hashtable<Object,Object> therefore you can see it as a synchronized form of java.util.HashMap<String, String>

Properties is nice to handle... properties : ) If you use it for other purposes, then your choice will depend on the concurrency management in your program

Jerome
  • 4,472
  • 4
  • 18
  • 18