Skip to content

Commit

Permalink
Avoid JDK-8015417 in Strings.equals()
Browse files Browse the repository at this point in the history
  • Loading branch information
garydgregory committed Sep 26, 2024
1 parent cdddb82 commit 6e78b38
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/main/java/org/apache/commons/lang3/Strings.java
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ public boolean equals(final CharSequence cs1, final CharSequence cs2) {

@Override
public boolean equals(final String s1, final String s2) {
return s1.equalsIgnoreCase(s2);
return s1 == null ? s2 == null : s1.equalsIgnoreCase(s2);
}

@Override
Expand Down Expand Up @@ -247,7 +247,7 @@ public boolean equals(final CharSequence cs1, final CharSequence cs2) {

@Override
public boolean equals(final String s1, final String s2) {
return s1.equals(s2);
return eq(s1, s2);
}

@Override
Expand Down Expand Up @@ -305,6 +305,15 @@ private static boolean containsAny(final ToBooleanBiFunction<CharSequence, CharS
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.
*/
Expand Down
26 changes: 26 additions & 0 deletions src/test/java/org/apache/commons/lang3/StringsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,21 @@
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());
Expand All @@ -54,4 +62,22 @@ public void testCaseSensitiveConstant() {
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));
}
}

0 comments on commit 6e78b38

Please sign in to comment.