问题
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 whyget
is returning null.myProp
does contain an entry for"material"
, so when you callprop1.getProperty("material")
, it will find that it doesn't have it directly, and check inmyProp
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