Avoid JDK-8015417 in Strings.equals()

This commit is contained in:
Gary Gregory 2024-09-26 11:01:53 -04:00
parent cdddb82e12
commit 6e78b38f05
2 changed files with 37 additions and 2 deletions

View File

@ -140,7 +140,7 @@ public abstract class Strings {
@Override
public boolean equals(final String s1, final String s2) {
return s1.equalsIgnoreCase(s2);
return s1 == null ? s2 == null : s1.equalsIgnoreCase(s2);
}
@Override
@ -247,7 +247,7 @@ public abstract class Strings {
@Override
public boolean equals(final String s1, final String s2) {
return s1.equals(s2);
return eq(s1, s2);
}
@Override
@ -305,6 +305,15 @@ public abstract class Strings {
return false;
}
/**
* Tests for equality in a null-safe manner.
*
* JDK-8015417.
*/
private static boolean eq(final Object o1, final Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
/**
* Ignores case when possible.
*/

View File

@ -21,13 +21,21 @@ import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;
/**
* Tests {@link Strings}.
*/
public class StringsTest {
public static Stream<Strings> stringsFactory() {
return Stream.of(Strings.CS, Strings.CI);
}
@Test
public void testBuilder() {
assertTrue(Strings.builder().setIgnoreCase(false).get().isCaseSensitive());
@ -54,4 +62,22 @@ public class StringsTest {
assertNotNull(Strings.CS);
assertTrue(Strings.CS.isCaseSensitive());
}
@ParameterizedTest
@MethodSource("stringsFactory")
public void testEqualsStrings(final Strings strings) {
final String nullStr = null;
assertTrue(strings.equals(nullStr, nullStr));
assertFalse(strings.equals(nullStr, ""));
assertFalse(strings.equals("", nullStr));
}
@ParameterizedTest
@MethodSource("stringsFactory")
public void testEqualsCharSequence(final Strings strings) {
final CharSequence nullCharSequence = null;
assertTrue(strings.equals(nullCharSequence, nullCharSequence));
assertFalse(strings.equals(nullCharSequence, ""));
assertFalse(strings.equals("", nullCharSequence));
}
}