为什么 ImmutableList.of() 和类似的方法禁止 null 元素?
摘要已经说明了一切。以下是 ImmutableList.createFromIterable()
中的相关代码片段:
if (element == null) {
throw new NullPointerException("at index " + index);
}
我已经多次遇到过这种情况,但不明白为什么通用库函数应该施加此限制。
编辑 1:通过“通用”,我会对 95% 的情况感到满意。但我认为我还没有编写过 100 个对 ImmutableList.of()
的调用,并且不止一次被这个问题困扰。但也许我是个异类。 :)
编辑 2:我想我最大的抱怨是,在与标准 java.util
集合交互时,这会产生“打嗝”。正如您在演讲中指出的,集合中 null
的问题可能会在远离插入这些 null 的位置处出现。但是,如果我有一长串代码,将空值放入标准集合中,并在另一端正确处理它们,那么我无法在任何时候替换谷歌集合类,因为它会立即抛出 NullPointerException 。
Summary pretty much says it all. Here's the relevant snippet of code in ImmutableList.createFromIterable()
:
if (element == null) {
throw new NullPointerException("at index " + index);
}
I've run into this several times and can't see why a general-purpose library function should impose this limitation.
Edit 1: by "general-purpose", I'd be happy with 95% of cases. But I don't think I've written 100 calls to ImmutableList.of()
yet, and have been bitten by this more than once. Maybe I'm an outlier, though. :)
Edit 2: I guess my big complaint is that this creates a "hiccup" when interacting with standard java.util
collections. As you pointed out in your talk, problems with null
s in collections can show up far away from where those nulls were inserted. But if I have a long chain of code that puts nulls in a standard collection at one end and handles them properly at the other, then I'm unable to substitute a google collections class at any point along the way, because it'll immediately throw a NullPointerException
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一般来说,在 Google Collections 中,开发人员不认为 null 应该是预期的通用参数。
In general in Google Collections the developers are of the group that does not believe that nulls should be an expected general purpose parameter.
来自 Guava 的 Github 页面
Guava 的立场主要是,还有其他方法可以避免集合中的 null 。例如,使用特定键获取一批项目。例如
From Guava's Github Page
The Guava position is largely, that there are other ways to avoid
null
s in collections. For example, fetching a batch of items with a specific key. E.g.原因之一是它允许在列表上工作的函数不必检查每个元素是否为 Null,从而显着提高了性能。
One reason is that it allows functions that work on the list not to have to check every element for Null, significantly improving performance.