I am getting an unexpected output from Properties.contains()
...
This is my code...
File file = new File("C:\\ravi\\non-existing.no");
Properties pro = System.getProperties();
pro.put("file", file);
System.out.println(pro.contains(file)); //PRINTS TRUE , AS EXPECTED
File file2 = file;
System.out.println(pro.contains(file2)); //PRINTS TRUE , AS EXPECTED
File file3 = new File("C:\\ravi\\non-existing.no");
System.out.println(pro.contains(file3)); //EXPECTED FALSE , BUT PRINTS TRUE
File file4 = new File("C:\\ravi\\non.no");
System.out.println(pro.contains(file4)); //PRINTS FALSE , AS EXPECTED
I am expecting the Properties
to check for the existance of the File
, however this doesn't seem to work. Could someone please help me explain why file3
doesn't work as I expect.
This is as expected, since
Properties#contains()
will callFile#equals()
, which in turn delegates tofs#compare()
which compares two abstract pathnames lexicographically. I.e, two files pointing to the same path will indeed be equal.I think your problem lies here :
From the Java docs:
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a Properties object. Their use is strongly discouraged as they allow the caller to insert entries whose keys or values are not Strings. The setProperty method should be used instead.
And when you call
contains()
on it, according to the Java docs:returns true if and only if some key maps to the value argument in this hashtable as determined by the equals method; false otherwise.
You see your problem now?
To clarify further:
When you do :
System.out.println(pro.contains(file3));
you end up doingfile.equals(file3)
, hencetrue
.And when you do :
System.out.println(pro.contains(file4));
you end up doingfile.equals(file4)
, hencefalse
.See Property class definition its
And
contains
is method of Hashtable which states -And it returns true if and only if some key maps to the value argument in this hashtable as determined by the equals method; false otherwise.