Difference between “get' VS ”getProperty"

ぐ巨炮叔叔 提交于 2019-12-13 12:56:04

问题


Properties myProp = new Properties();
myProp.put("material", "steel");

Properties prop1 = new Properties(myProp);

System.out.println(prop1.get("material") + ", " + prop1.getProperty("material"));
// outputs "null, steel"

Isn't get similar to getProperty in the sense that it returns the entries/attributes of an Object? Why is it not returning 'steel' when using get?


回答1:


get is inherited from Hashtable, and is declared to return Object.

getProperty is introduced by Properties, and is declared to return String.

Note thatgetProperty will consult the "defaults" properties which you can pass into the constructor for Properties; get won't. In most cases they'll return the same value though. In the example you've given, you are using a default backing properties:

  • prop1 doesn't directly contain an entry for "material", hence why get is returning null.
  • myProp does contain an entry for "material", so when you call prop1.getProperty("material"), it will find that it doesn't have it directly, and check in myProp instead, and find "steel" there.



回答2:


A look at the docs shows that get is inherited, and returns Object whereas getProperty is a member of Properties and returns the String.

Seemingly they should return the same, however from the docs again:

If the key is not found in this property list, the default property list, and its defaults, recursively, are then checked.

So it is best to use getProperty as it will return the default if it is not found.




回答3:


Your second Properties object (props or prop1?), has no properties added directly to it. It only uses myProp as defaults. So those values never get added to the backing HashMap. Properties.getProperty() doesn't find "material" in the backing HashMap so it can look in the defaults. But the inherited HashMap.get() only looks in the backing HashMap and not in the defaults that you passed into the constructor.



来源:https://stackoverflow.com/questions/11104395/difference-between-get-vs-getproperty

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!