api doc说:确保索引在数组,列表或大小的字符串中指定有效元素.
但是在这个方法中传递'target'数组或列表字符串?
内的元件Array,List并且String可以使用基于0的索引来访问.
假设您要使用索引从List访问特定元素.在调用之前list.get(index),您可以使用以下内容检查它index 是否介于0和之间list.size()以避免IndexOutOfBoundsException:
if (index < 0) {
throw new IllegalArgumentException("index must be positive");
} else if (index >= list.size()){
throw new IllegalArgumentException("index must be less than size of the list");
}
Run Code Online (Sandbox Code Playgroud)
Preconditions类的目的是用更紧凑的检查替换这种检查
Preconditions.checkElementIndex(index,list.size());
Run Code Online (Sandbox Code Playgroud)
因此,您不需要传递整个目标列表实例.相反,您只需要将目标列表的大小传递给此方法.
您不需要“目标”来知道 int 索引对于给定大小的列表、字符串或数组是否有效。如果index >= 0 && index < [list.size()|string.length()|array.length]那么它是有效的,否则不是。
| 归档时间: |
|
| 查看次数: |
3236 次 |
| 最近记录: |