[LANG-1615] - ArrayUtils contains && indexOf fails to handle Float.NaN (#651)

* LANG-1615 - ArrayUtils contains && indexOf fails to handle Float.NaN

* Change var name

* Fix checkstyle spaces black

* Fix checkstyle spaces black
This commit is contained in:
Arturo Bernal 2020-11-15 23:37:54 +01:00 committed by GitHub
parent 08d1f66236
commit 2ccc58e344
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 23 additions and 5 deletions

View File

@ -2518,8 +2518,10 @@ public class ArrayUtils {
if (startIndex < 0) {
startIndex = 0;
}
final boolean searchNaN = Float.isNaN(valueToFind);
for (int i = startIndex; i < array.length; i++) {
if (valueToFind == array[i]) {
final float element = array[i];
if (valueToFind == element || (searchNaN && Float.isNaN(element))) {
return i;
}
}

View File

@ -309,6 +309,14 @@ public class ArrayUtilsTest {
assertFalse(ArrayUtils.contains(array, (float) 99));
}
@Test
public void testContainsFloatNaN() {
float[] array = new float[] { Float.NEGATIVE_INFINITY, Float.NaN, Float.POSITIVE_INFINITY };
assertTrue(ArrayUtils.contains(array, Float.POSITIVE_INFINITY));
assertTrue(ArrayUtils.contains(array, Float.NEGATIVE_INFINITY));
assertTrue(ArrayUtils.contains(array, Float.NaN));
}
@Test
public void testContainsInt() {
int[] array = null;
@ -1124,6 +1132,14 @@ public class ArrayUtilsTest {
assertEquals(-1, ArrayUtils.indexOf(array, (float) 99));
}
@Test
public void testIndexOfFloatNaN() {
float[] array = new float[] { Float.NEGATIVE_INFINITY, Float.NaN, Float.POSITIVE_INFINITY, Float.NaN };
assertEquals(0, ArrayUtils.indexOf(array, Float.NEGATIVE_INFINITY));
assertEquals(1, ArrayUtils.indexOf(array, Float.NaN));
assertEquals(2, ArrayUtils.indexOf(array, Float.POSITIVE_INFINITY));
}
@SuppressWarnings("cast")
@Test
public void testIndexOfFloatWithStartIndex() {