[英]Stream different data types
I'm getting my head around Streams API. 我正在研究Streams API。
What is happening with the 2 in the first line? 第一行中2发生了什么? What data type is it treated as?
它被视为什么数据类型? Why doesn't this print true ?
为什么这不是真的 ?
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i=="2"));
The second part of this question is why doesn't the below code compile ( 2 is not in quotes )? 这个问题的第二部分是为什么下面的代码不能编译( 2不在引号中 )?
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i==2));
In the first snippet, you are creating a Stream
of Object
s. 在第一个片段中,您将创建一个
Object
Stream
。 The 2
element is an Integer
, so comparing it to the String
"2" returns false. 2
元素是一个Integer
,因此将它与String
“2”进行比较会返回false。
In the second snippet, you can't compare an arbitrary Object to the int
2, since there is no conversion from Object
to 2
. 在第二个片段中,您无法将任意Object与
int
2进行比较,因为没有从Object
到2
转换。
For the first snippet to return true, you have to change the last element of the Stream to a String
(and also use equals
instead of ==
in order not to rely on the String
pool): 要使第一个片段返回true,您必须将Stream的最后一个元素更改为
String
(并且还使用equals
而不是==
以便不依赖于String
池):
System.out.println(Stream.of("hi", "there", "2").anyMatch(i->i.equals("2")));
The second snippet can be fixed by using equals
instead of ==
, since equals
exists for any Object
: 可以使用
equals
而不是==
来修复第二个片段,因为任何Object
存在equals
:
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i.equals(2)));
You should instead make use of: 你应该使用:
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i.equals(2)));
The reason for that is the comparison within the anyMatch
you're doing is for i
which is an Object
(from the stream) and is incompatible with an int
. 这样做的原因是你正在做的
anyMatch
的比较是i
,它是一个Object
(来自流)并且与int
不兼容。
Also, note that the first part compiles successfully since you are comparing an integer(object) with an object string "2"
in there and hence returns false. 另请注意,第一部分成功编译,因为您将整数(对象)与对象字符串
"2"
进行比较,因此返回false。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.