You are viewing a plain text version of this content. The canonical link for it is here.
Posted to dev@thrift.apache.org by "Liu Jiayu (Jira)" <ji...@apache.org> on 2022/04/14 03:48:00 UTC
[jira] [Commented] (THRIFT-5483) Support customized comparator in Java
[ https://issues.apache.org/jira/browse/THRIFT-5483?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17522041#comment-17522041 ]
Liu Jiayu commented on THRIFT-5483:
-----------------------------------
[~jt2594838] in my opinion this isn't something that should be done in thrift level. You can almost always do this outside of framework, by defining your own comparator:
{code:java}
public static Comparator<Xtruct> alternativeComparator = new Comparator<Xtruct>() {
@Override
public int compare(Xtruct o1, Xtruct o2) {
int result = o1.string_thing.compareTo(o2.string_thing);
if (result != 0) {
return result;
}
return o1.compareTo(o2);
}
};
private static final java.util.TreeMap<Xtruct, java.lang.String> map = new java.util.TreeMap(alternativeComparator); {code}
Using [https://guava.dev/releases/21.0/api/docs/com/google/common/collect/ComparisonChain.html] can also simplify the definition of customized comparator.
> Support customized comparator in Java
> -------------------------------------
>
> Key: THRIFT-5483
> URL: https://issues.apache.org/jira/browse/THRIFT-5483
> Project: Thrift
> Issue Type: Improvement
> Components: Java - Compiler
> Reporter: Tian Jiang
> Priority: Major
>
> The generated comparator (and hash code) of Thrift Structs compares two objects by all of their fields, which may cause trouble when used in hash structures.
> For example, I define a struct like:
> {code:java}
> struct Person{
> 1: required i64 id
> 2: required string phoneNumber
> }
> {code}
> The id of a Person is final, while its phoneNumber can be changed.
> Then I use it as a key in a map to record a Person's supervisors:
> {code:java}
> Map<Person, Person> supervisorMap;
> {code}
> Apparently, as the generated comparator of Person will use both id and phoneNumber for comparison and hash if I change the phoneNumber of a Person, I can no longer get it from the map as its hash value changes and it will be distributed to another hash slot.
> Therefore, I wish I could specify the fields that are to be used in comparator and hash code generation. One preferable grammar may be like:
> {code:java}
> struct Person{
> 1: required comparable i64 id
> 2: required string phoneNumber
> }
> {code}
> Then the generated comparator and hash code will only use fields marked with `comparable`, and if no fields are marked with comparable, Java's default comparison and hashcode (using object address) will be used.
--
This message was sent by Atlassian Jira
(v8.20.1#820001)