Implement DefaultHeaders.HeaderEntry.equals()

Motivation:

HeaderEntry.equals() inherets Object.equals() which simply check if two objects are the same.
So it returns false even when two HeaderEntry objects have the same name and value.

Modifications:

Implement HeaderEntry.equals() that follows the specification of Map.Entry.equals().
https://docs.oracle.com/javase/9/docs/api/java/util/Map.Entry.html#equals-java.lang.Object-

Result:

HeaderEntry.equals() returns true if two HeaderEntry objects have the same name and value.
This commit is contained in:
ryu1-sakai 2018-02-15 02:37:46 +09:00 committed by Norman Maurer
parent ad6af3250c
commit c1d0d88f0a
2 changed files with 33 additions and 0 deletions

View File

@ -1170,5 +1170,20 @@ public class DefaultHeaders<K, V, T extends Headers<K, V, T>> implements Headers
public final String toString() {
return key.toString() + '=' + value.toString();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Map.Entry)) {
return false;
}
Map.Entry<?, ?> other = (Map.Entry<?, ?>) o;
return (getKey() == null ? other.getKey() == null : getKey().equals(other.getKey())) &&
(getValue() == null ? other.getValue() == null : getValue().equals(other.getValue()));
}
@Override
public int hashCode() {
return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode());
}
}
}

View File

@ -441,6 +441,24 @@ public class DefaultHeadersTest {
assertFalse(headers.contains(of("name1"), of("value3")));
}
@Test
public void testEntryEquals() {
Map.Entry<CharSequence, CharSequence> same1 = newInstance().add("name", "value").iterator().next();
Map.Entry<CharSequence, CharSequence> same2 = newInstance().add("name", "value").iterator().next();
assertEquals(same1, same2);
assertEquals(same1.hashCode(), same2.hashCode());
Map.Entry<CharSequence, CharSequence> nameDifferent1 = newInstance().add("name1", "value").iterator().next();
Map.Entry<CharSequence, CharSequence> nameDifferent2 = newInstance().add("name2", "value").iterator().next();
assertNotEquals(nameDifferent1, nameDifferent2);
assertNotEquals(nameDifferent1.hashCode(), nameDifferent2.hashCode());
Map.Entry<CharSequence, CharSequence> valueDifferent1 = newInstance().add("name", "value1").iterator().next();
Map.Entry<CharSequence, CharSequence> valueDifferent2 = newInstance().add("name", "value2").iterator().next();
assertNotEquals(valueDifferent1, valueDifferent2);
assertNotEquals(valueDifferent1.hashCode(), valueDifferent2.hashCode());
}
@Test
public void getAllReturnsEmptyListForUnknownName() {
TestDefaultHeaders headers = newInstance();