How to use Google Guava's Preconditions.checkElementIndex?
The api doc said: Ensures that index specifies a valid element in an array, list or string of size size.
But where p开发者_如何学运维ass the 'target' array or list string in this method?
The element inside the Array
, List
and String
can be accessed using the 0-based index.
Suppose you want to access a particular element from a List using an index .Before calling list.get(index)
, you may use the following to check this index
is between 0 and list.size()
to avoid 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");
}
The purpose of Preconditions
class is to replace this checking with the more compact one
Preconditions.checkElementIndex(index,list.size());
So , you don't need to pass the whole target list instance .Instead , you just need to pass the size of the target list to this method.
The method Precondition.checkElementIndex(...) does not care about the 'target'. You simply pass the size
and the index
, as follows:
public String getElement(List<String> list, int index) {
Preconditions.checkElementIndex(index, list.size(), "The given index is not valid");
return list.get(index);
}
According to Guava's reference, the method checkElementIndex
could be implemented as follows:
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;
}
}
As you can see, there's no need for it to know the List, Array, or whatever.
You don't need the "target" to know whether an int index is valid for a given size of list, string, or array. If index >= 0 && index < [list.size()|string.length()|array.length]
then it's valid, else not.
精彩评论