我在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(...)呢?什么原因?
也许,它只是避免代码重复,因为否则它将是这样的:
new IndexOutOfBoundsException(outOfBoundsMessage(..., ...))
Run Code Online (Sandbox Code Playgroud)
但outOfBounds*方法是private,所以通过设计有人应该调用包装器return Preconditions.checkIndex(index, length, null)
| 归档时间: |
|
| 查看次数: |
227 次 |
| 最近记录: |