我正在研究 Streams API。
第一行的 2 发生了什么?它被视为什么数据类型?为什么这不打印 true?
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i=="2"));
这个问题的第二部分是为什么下面的代码不能编译(2 不在引号中)?
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i==2));
最佳答案
在第一个片段中,您正在创建一个 Object
的 Stream
。 2
元素是一个 Integer
,因此将它与 String
“2”进行比较会返回 false。
在第二个片段中,您无法将任意对象与 int
2 进行比较,因为没有从 Object
到 2
的转换>.
对于返回 true 的第一个代码段,您必须将 Stream 的最后一个元素更改为 String
(并且还使用 equals
而不是 ==
为了不依赖于 String
池):
System.out.println(Stream.of("hi", "there", "2").anyMatch(i->i.equals("2")));
第二个片段可以通过使用 equals
而不是 ==
来修复,因为 equals
存在于任何 Object
:
System.out.println(Stream.of("hi", "there",2).anyMatch(i->i.equals(2)));
关于java - 流式传输不同的数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45791489/