This commit is contained in:
Rob Tompkins 2018-08-09 15:15:38 -04:00
commit 0bca64d75e
2 changed files with 31 additions and 0 deletions

View File

@ -8672,4 +8672,20 @@ public class ArrayUtils {
swap(array, i - 1, random.nextInt(i), 1);
}
}
/**
* Returns whether a given array can safely be accessed at the given index.
* @param <T> the component type of the array
* @param array the array to inspect, may be null
* @param index the index of the array to be inspected
* @return Whether the given index is safely-accessible in the given array
* @since 3.8
*/
public static <T> boolean isArrayIndexValid(T[] array, int index){
if(getLength(array) == 0 || array.length <= index){
return false;
}
return index >= 0;
}
}

View File

@ -5111,4 +5111,19 @@ public class ArrayUtilsTest {
assertTrue("Element " + element + " not found", ArrayUtils.contains(array1, element));
}
}
@Test
public void testIsArrayIndexValid(){
assertFalse(ArrayUtils.isArrayIndexValid(null, 0));
String[] array = new String[1];
//too big
assertFalse(ArrayUtils.isArrayIndexValid(array, 1));
//negative index
assertFalse(ArrayUtils.isArrayIndexValid(array, -1));
//good to go
assertTrue(ArrayUtils.isArrayIndexValid(array, 0));
}
}