Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between "get' VS "getProperty"

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?

like image 919
bouncingHippo Avatar asked Jun 19 '12 15:06

bouncingHippo


2 Answers

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.
like image 57
Jon Skeet Avatar answered Nov 05 '22 10:11

Jon Skeet


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.

like image 32
NominSim Avatar answered Nov 05 '22 09:11

NominSim