Unexpected output from Properties.contains()

2019-08-15 00:16发布

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.

3条回答
聊天终结者
2楼-- · 2019-08-15 00:23

This is as expected, since Properties#contains() will call File#equals(), which in turn delegates to fs#compare() which compares two abstract pathnames lexicographically. I.e, two files pointing to the same path will indeed be equal.

查看更多
The star\"
3楼-- · 2019-08-15 00:34

I think your problem lies here :

 pro.put("file", file);

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 doing file.equals(file3) , hence true.

And when you do :System.out.println(pro.contains(file4)); you end up doing file.equals(file4) , hence false.

查看更多
唯我独甜
4楼-- · 2019-08-15 00:45

See Property class definition its

public class Properties extends Hashtable<Object,Object>

And contains is method of Hashtable which states -

    Tests if some key maps into the specified value in this hashtable.
    This operation is more expensive than the containsKey method.
    Note that this method is identical in functionality to containsValue,
   (which is part of the Map interface in the collections framework).

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.

查看更多
登录 后发表回答