api doc说:确保index指定一个大小为大小的数组、列表或字符串中的有效元素。
但是在什么地方传递这个方法中的“target”数组或列表字符串呢?
发布于 2011-08-02 11:50:50
可以使用从0开始的索引访问Array、List和String中的元素。
假设您想要使用调用list.get(index)的索引.Before访问列表中的特定元素,您可以使用以下命令检查此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");
}Preconditions类的目的是用更紧凑的检查替换这种检查
Preconditions.checkElementIndex(index,list.size());因此,您不需要传递整个目标列表实例.Instead,只需将目标列表的大小传递给此方法。
发布于 2011-08-02 11:12:42
方法Precondition.checkElementIndex(...)不关心“目标”。您只需传递size和index,如下所示:
public String getElement(List<String> list, int index) {
Preconditions.checkElementIndex(index, list.size(), "The given index is not valid");
return list.get(index);
}根据Guava's reference的说法,checkElementIndex方法可以实现如下:
public class Preconditions {
public static int checkElementIndex(int index, int size) {
if (size < 0) throw new IllegalArgumentException();
if (index < 0 || index >= size) throw new IndexOutOfBoundsException();
return index;
}
}正如您所看到的,它不需要知道列表、数组或其他任何东西。
发布于 2011-08-02 10:55:31
您不需要"target“来知道int索引对于给定大小的list、string或array是否有效。如果为index >= 0 && index < [list.size()|string.length()|array.length],则它是有效的,否则无效。
https://stackoverflow.com/questions/6906423
复制相似问题