Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Google Guava's Preconditions.checkElementIndex?

Tags:

java

guava

The api doc said: Ensures that index specifies a valid element in an array, list or string of size size.

But where pass the 'target' array or list string in this method?

like image 571
Sean Avatar asked Aug 02 '11 01:08

Sean


1 Answers

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.

like image 133
Ken Chan Avatar answered Nov 15 '22 05:11

Ken Chan