Skip to content

Commit

Permalink
Add hashcode and equals methods to LatLong (#179)
Browse files Browse the repository at this point in the history
* Add hashcode and equals methods to LatLong

Discovered that LatLong doesn't actually implement hashcode() or
equals(), so we can't actually put it into a Set<> or call distinct() on
it in a stream.

Used IntelliJ IDEA's automatic generation of these things. Happy to
change the implementation if desired.

* Performance fix

Objects.hashCode() under the hood creates a bunch of objects we don't
need, so directly create and aggregate the hashcodes.
  • Loading branch information
Anusien authored Apr 16, 2024
1 parent 73d2782 commit 95dd6f2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
17 changes: 17 additions & 0 deletions geo/src/main/java/com/github/davidmoten/geo/LatLong.java
Original file line number Diff line number Diff line change
Expand Up @@ -61,4 +61,21 @@ public String toString() {
return builder.toString();
}

@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final LatLong latLong = (LatLong) o;
return Double.compare(lat, latLong.lat) == 0 && Double.compare(lon, latLong.lon) == 0;
}

@Override
public int hashCode() {
return 31 * Double.hashCode(lat) + Double.hashCode(lon);
}

}
15 changes: 13 additions & 2 deletions geo/src/test/java/com/github/davidmoten/geo/LatLongTest.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package com.github.davidmoten.geo;

import static org.junit.Assert.assertEquals;

import org.junit.Test;

import static org.junit.Assert.assertEquals;

/**
* Unit tests for {@link LatLong}.
*
Expand All @@ -18,4 +18,15 @@ public void testToString() {
new LatLong(10, 20).toString());
}

@Test
public void testHashCode() {
float lat = 20.05f;
float lon = -15.5f;
LatLong a = new LatLong(lat, lon);
LatLong b = new LatLong(lat, lon);

assertEquals(a.hashCode(), b.hashCode());
assertEquals(a, b);
}

}

0 comments on commit 95dd6f2

Please sign in to comment.