java - "but the compiler doesn' t 知道这个 "- what' 的意义吗?

标签 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
    } 
    ...
}

为什么不直接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/

相关文章:

java - 使用 Spring Security + CAS 获取循环重定向,但应该可以工作

java - jlink 选项 compress 有什么作用?

java - RuntimeException : Package jdk. 模块 jrt.fs 和模块 java.base 中的 internal.jimage.decompressor

java - Ant:以编程方式创建 JUnit 报告任务

java - 多个端口 (8080,8009) 已被使用

java - 如何将枚举与 switch 语句一起使用?

java - 如何打印一个也有双变量的字符串数组?

Java 9 ServiceLoader 运行时模块加载和替换

android-studio - Android Gradle 依赖编译不适用于 Java 9

version - Java 9 版本字符串方案中的第四个数字意味着什么?