Trades.java class is incorrectly comparing ID strings
See original GitHub issueTrades.java contains the following:
@Override
public int compare(Trade trade1, Trade trade2) {
return trade1.getId().compareTo(trade2.getId());
}
Since .getId()
returns a String, comparing two Strings using compareTo
is a lexicographical comparison, and would not work reliably, especially when the length of the String is different.
Consider this example:
public static void main(String[] args) {
String id = "100";
// check if the value is less than 100
System.out.println(id.compareTo("99"));
// check if value is equal to 100
System.out.println(id.compareTo("100"));
// check if value is greater than 100
System.out.println(id.compareTo("101"));
}
Console:
-8
0
-1
"100".compareTo("99")
returns a negative number which is lexicographically correct, but if these are trade Ids, then this is a bug.
We should therefore change the TradeIDComparator in Trades.java to convert the String into a BigInteger or Integer prior to the comparison.
something like this:
@Override
public int compare(Trade trade1, Trade trade2) {
BigInteger id1 = new BigInteger(trade1.getId());
BigInteger id2 = new BigInteger(trade2.getId());
return id1.compareTo(id2);
}
Issue Analytics
- State:
- Created 5 years ago
- Comments:5 (3 by maintainers)
Top Results From Across the Web
java - Comparing two identical strings with == returns false
In your code, you are comparing an Object with a String literal (also an object), which is not the same as comparing the...
Read more >Comparable Interface: Comparing Strings - Saylor Academy
Objects that have an ordering are compared using the compareTo() method. ... When strings are compared, case-sensitive dictionary order is used.
Read more >Groovy Language Documentation
class Component { Integer id String name } class CompositeObject implements Iterable<Component> { def components = [ new Component(id: 1, name: 'Foo'), ...
Read more >How to run an if statement on a string variable (which value is ...
Use the [code ]string.equals(Object other)[/code] function to compare strings, not the [code ]==[/code] operator. The function checks the actual contents of ...
Read more >Java 8 Date Time - 20 Examples of LocalDate, LocalTime ...
Example 20 - How to convert Date to String in Java 8, formatting dates. In the last two examples, though we have been...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
@shimonm I addressed your problem in https://github.com/knowm/XChange/pull/2839, dealing with hexadecimal IDs as well.
Thank you! closing