How to use Google Guava Preconditions.checkElementIndex?

Api doc said: ensures that the index indicates a valid element in an array, list, or size string.

But where to pass this array to "target" or a list string in this method?

+4
source share
3 answers

An element inside Array , List and String can be obtained using an index based on 0.

Suppose you want to access a specific item from a list using an index. Before calling list.get(index) you can use the following to verify that this index is between 0 and list.size() to avoid an 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 goal of the Preconditions class is to replace this check with a more compact one.

 Preconditions.checkElementIndex(index,list.size()); 

So you do not need to pass the entire instance of the target list. Instead, you just need to pass the size of the target list to this method.

+6
source

The Precondition.checkElementIndex (...) method does not care about the "target". You simply pass size and 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 the Guava link, the checkElementIndex method can 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, he does not need to know a list, an array, or anything else.

+3
source

You do not need a “target” to find out if the int index is valid for the given size of the list, string or array. If index >= 0 && index < [list.size()|string.length()|array.length] , then it is valid, otherwise not.

+1
source

All Articles