Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.math.BigDecimal;

/**
Expand All @@ -27,7 +26,7 @@
* @author Inderjeet Singh
*/
@SuppressWarnings("serial") // ignore warning about missing serialVersionUID
public final class LazilyParsedNumber extends Number {
public final class LazilyParsedNumber extends Number implements Comparable<LazilyParsedNumber> {
private final String value;

/**
Expand Down Expand Up @@ -82,7 +81,7 @@ public String toString() {
* If somebody is unlucky enough to have to serialize one of these, serialize it as a BigDecimal
* so that they won't need Gson on the other side to deserialize it.
*/
private Object writeReplace() throws ObjectStreamException {
private Object writeReplace() {
return asBigDecimal();
}

Expand All @@ -92,6 +91,17 @@ private void readObject(ObjectInputStream in) throws IOException {
throw new InvalidObjectException("Deserialization is unsupported");
}

/**
* Compares this LazilyParsedNumber with the specified LazilyParsedNumber. The comparison is
* lexicographical, based on the string values of the two numbers, so it does not in general
* correspond to numeric comparison. For numeric comparison, call {@link #asBigDecimal()} on both
* numbers and compare the results.
*/
@Override
public int compareTo(LazilyParsedNumber other) {
return value.compareTo(other.value);
}

@Override
public int hashCode() {
return value.hashCode();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;

public class LazilyParsedNumberTest {
Expand All @@ -40,6 +43,14 @@ public void testEquals() {
assertThat(n1.equals(n1Another)).isTrue();
}

@Test
public void testCompareTo() {
List<String> inputs = Arrays.asList(new String[] {"1", "1.0", "2", "1e6"});
Collections.sort(inputs);
List<String> expected = Arrays.asList(new String[] {"1", "1.0", "1e6", "2"});
assertThat(inputs).isEqualTo(expected);
}

@Test
public void testJavaSerialization() throws IOException, ClassNotFoundException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
Expand Down