实施具有动态生成属性的Sortable类

问题描述 投票:0回答:1

我想要一个可以按属性排序的类(可能使用Comparable和Comparator)。但是,该类具有普通的类属性,而不是“键值对列表”。

class Normal
{
   String attrib1;
   String attrib2;
   int attrib3;
}

此类属性

class Special
{
    Map<String,Object> attributes =new HashMap<String,Object>()
}

基本上,类属性是根据场景动态生成的。因此,在给定的情况下,对象属性哈希图将具有,

attrib1 : "value1"
attrib2 : "value2"
attrib3 : 3

因此,我需要实现类'Special',其中可以通过给定的样式对类'Special'的对象列表进行排序(等:按attrib3排序)。

java sorting generics comparator comparable
1个回答
2
投票

首先:

public class Special {

     Map<String, Comparable> hashMap = new HashMap<String, Comparable>();
}

这些值必须实现Comparable接口。

然后您可以使用类似的比较器:

public class SpecialComparator implements Comparator<Special> {

    private String key;

    public SpecialComparator(String key) {
        this.key = key;
    }

    @Override
    public int compare(Special o1, Special o2) {
        // manage cases where o1 or o2 do not contains key
        return o1.hashMap.get(key).compareTo(o2.hashMap.get(key));
    }

}

最后排序您的列表:

Collections.sort(list, new SpecialComparator("somekey"));
© www.soinside.com 2019 - 2024. All rights reserved.