When to use Properties and when Map in Java?

前端 未结 9 646
抹茶落季
抹茶落季 2020-12-16 15:29

Difference between Map and Properties as both have key-value pair.

相关标签:
9条回答
  • 2020-12-16 15:52

    Use a class that's implementing the Map interface, but isn't the Properties class. The Properties class is broken. Since it's a Hashtable underneath, there are methods that would break the otherwise consistent String-to-String mapping. Its invariant is very easily broken (both mistakenly and on purpose). Use anything else implementing the Map interface. If you're aiming for thread safety - use Collections.synchronizedMap(myUnsyncdMap) to create one.

    Ideally, there is no difference between the two classes other than 1 or two methods mentioned in the other answers. However the Properties implementation is actually bizarre - other classes, deriving from the Map interface, are much safer, provide better statical typing and are probably faster (depending on what you need). Taking a quick look at the implementation (specifically which class it derives from) should be enough to convince you to avoid it :)

    0 讨论(0)
  • 2020-12-16 15:58

    Properties is a Facade for Map<String,String> + some I/O methods.

    Do you need the I/O methods ? use it : don't.

    0 讨论(0)
  • 2020-12-16 16:00

    A per key default system is another feature of Properties not present in Hashtable is . E.g.:

    Properties p0 = new Properties();
    p0.setProperty("a", "0");
    p0.setProperty("b", "1");
    Properties p1 = new Properties(p0);
    p1.setProperty("a", "10");
    assert p1.getProperty("a").equals("10");
    assert p1.getProperty("b").equals("1");
    assert p1.getProperty("c") == null;
    

    Defaults are searched recursively in parent properties.

    0 讨论(0)
提交回复
热议问题