[英]Hashmap get() method returns null but when comparing with null prints false
There is a hashmap有一个hashmap
HashMap<String,ArrayList<String>> hm = new HashMap<>();
It has these values它有这些值
entertain - have,
some - one,
very - extremely, actually, really, super,
auto - car,
lunch - meal,
wagon - car,
truck - car,
Problem statement问题陈述
System.out.println("test " + hm.get("delicious")); //prints null
System.out.println("test " + hm.get("delicious") == null); //prints false
why is the second print statement printing false, should it not print true?为什么第二个打印语句打印为假,不应该打印为真?
The expression passed to the println
method is evaluated from left to right.传递给
println
方法的表达式是从左到右计算的。 First the String
"test " is concatenated to hm.get("delicious")
, and only then the output is compared to null
.首先将
String
“test”连接到hm.get("delicious")
,然后才将 output 与null
进行比较。
Therefore:所以:
System.out.println("test " + hm.get("delicious") == null);
is equivalent to:相当于:
System.out.println(("test " + hm.get("delicious")) == null);
"test " +hm.get("delicious")
is definitely not null
(it's actually equal to the String
"test null"), so false
is printed. "test " +hm.get("delicious")
肯定不是null
(它实际上等于String
"test null"),所以打印的是false
。
System.out.println("test " + (hm.get("delicious")==null));
will print "test true".将打印“测试为真”。
Before we try to find a solution to this question, we should understand that what exactly is null
in memory?在我们试图找到这个问题的解决方案之前,我们应该了解
null
中的 null 到底是什么? Or What is the null
value in Java?或者 Java 中的
null
值是多少?
First of all, null
is not a valid object instance, so there is no memory allocated for it.首先,
null
不是有效的 object 实例,因此没有为其分配 memory。 It is simply a value that indicates that the object reference is not currently referring to an object.它只是一个值,表明 object 引用当前不是指 object。
Let's come to the actual question.让我们来看看实际的问题。 the following code is internally used by java to compare.
java内部使用以下代码进行比较。
public static boolean compare(String str1, String str2) {
return (str1 == null ? str2 == null : str1.equals(str2));
}
I hope, now you can understand why your program says false
.我希望,现在你可以理解为什么你的程序说
false
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.