所以我不想避免IndexOutofBounds错误;但是,我想知道如何知道何时击中它而不会使程序崩溃。
List<String> pool = new ArrayList<>();
pool.add("a");
boolean checked = (pool.get(1) == null); //I know this doensn't work
System.out.println(checked); //I want false
因此,在此示例中,很明显我的List池的索引1中不存在任何内容。是否有可能获得一个布尔值?或者是否可以检查是否已经达到列表的结尾而不执行i&lt;则为list.size()?谢谢你的时间和帮助。
答案 0 :(得分:2)
它被称为try-catch块:
boolean hasValue;
try {
hasValue = (pool.get(i) != null);
} catch (IndexOutOfBoundsException e) {
hasValue = false;
}
// hasValue == true if non-null value found at index i
然而,这是anti-pattern名为“exceptions as flow control”。
答案 1 :(得分:0)
答案是否定的。您可以查看the docs并查看除了检查尺寸之外的其他方法,如果存在,则无法获取&#34;或者找出&#34;索引是否存在&#34;。
尝试访问索引并捕获异常是可能的,但不推荐,因为catching exceptions is an expensive operation in java