我在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
}
...
}
为什么不直接throw new IndexOutOfBoundsException(...)
?这是什么原因?
最佳答案
也许,这只是为了避免代码重复,否则它会是这样的:
new IndexOutOfBoundsException(outOfBoundsMessage(..., ...))
但是 outOfBounds*
方法是私有(private)的
,所以设计上应该有人调用包装器,例如 return Preconditions.checkIndex(index, length, null)
关于java - "but the compiler doesn' t 知道这个 "- what' 的意义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48214547/