"但是编译器不知道这个" - 这是什么意思?

And*_*niy 11 java java-9

我在java.util.ImmutableCollections课堂上遇到过这样的代码和评论:

static final class List0<E> extends AbstractImmutableList<E> {
    ...
    @Override
    public E get(int index) {
        Objects.checkIndex(index, 0); // always throws IndexOutOfBoundsException
        return null;                  // but the compiler doesn't know this
    } 
    ...
}
Run Code Online (Sandbox Code Playgroud)

为什么不throw new IndexOutOfBoundsException(...)呢?什么原因?

And*_*niy 7

也许,它只是避免代码重复,因为否则它将是这样的:

new IndexOutOfBoundsException(outOfBoundsMessage(..., ...)) 
Run Code Online (Sandbox Code Playgroud)

outOfBounds*方法是private,所以通过设计有人应该调用包装器return Preconditions.checkIndex(index, length, null)

  • 是的,避免代码重复.努力集中所有这些索引检查和异常消息构造.这不仅会影响集合实现和`Arrays`实用程序方法,还会影响NIO缓冲区,`CharSequence`实现等等.很多地方,很多代码重复.请注意,这是一个允许您的应用程序参与的[新API方法](https://docs.oracle.com/javase/9​​/docs/api/java/util/Objects.html#checkIndex-int-int-)在这个中央处理.不过,我会使用`throw new AssertionError()`而不是`return null;`这里...... (7认同)