来自Properties.contains()的意外输出 [英] Unexpected output from Properties.contains()

查看:45
本文介绍了来自Properties.contains()的意外输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从Properties.contains() ...

这是我的代码...

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

我期望Properties检查File的存在,但是这似乎不起作用.有人可以帮我解释为什么file3不能按我预期的那样工作.

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.

推荐答案

我认为您的问题出在这里:

I think your problem lies here :

 pro.put("file", file);

来自Java文档:

因为属性是从Hashtable继承的,所以put和putAll方法可以应用于Properties对象.强烈建议不要使用它们,因为它们允许调用方插入键或值不是String的条目.应该改用setProperty方法.

根据Java文档,当您在其上调用contains()时:

And when you call contains() on it, according to the Java docs:

当且仅当某些键映射到由equals方法确定的此哈希表中的value参数时,返回true.否则为false.

您现在看到问题了吗?

进一步说明:

当您执行:System.out.println(pro.contains(file3));时,您最终将执行file.equals(file3),因此执行的是true.

When you do :System.out.println(pro.contains(file3)); you end up doing file.equals(file3) , hence true.

然后,当您执行:System.out.println(pro.contains(file4));时,您最终将执行file.equals(file4),因此执行的是false.

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

这篇关于来自Properties.contains()的意外输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆