簡體   English   中英

Java-使庫類具有可比性

[英]Java - Make a library class comparable

是否可以在不擴展庫類的情況下使它們具有可比性?

import org.json.JSONObject;

LinkedList<JSONObject> list = getListFromFunction();

TreeSet<JSONObject> treeSet = new TreeSet<JSONObject>(list);

由於JSONObject不具有可比性,因此無法在此處創建TreeSet 如何將自定義比較器“附加”到JSONObject
(有一個獨特的屬性,請說“ _some_id”以進行比較)

在這種情況下,我們可以使用Comparator來處理這種情況。 請參考以下示例。

主班

public class ComparatorTest{
     public static void main(String[] ar) {
        // System.out.println(new Sample().stringTimes("vivek", 5));
        JSONObject emp1 = new JSONObject();
        JSONObject emp2 = new JSONObject();
        try {
            emp1.put("department", "IT");
            emp1.put("name", "bvivek");
            emp1.put("id", 1);

            emp2.put("department", "IT");
            emp2.put("name", "avikash");
            emp2.put("id", 2);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        List<JSONObject> employess = new ArrayList<JSONObject>();
        employess.add(emp1);//add to list
        employess.add(emp2);//add to list
        System.out.println(employess);//unsorted, as is
        Collections.sort(employess, new JSONComparator("name"));
        System.out.println(employess);//sorted as per the field
        //using treeSet
        TreeSet<JSONObject> jsonInTree = new TreeSet<JSONObject>(new JSONComparator("id"));
        jsonInTree.addAll(employess);
        System.out.println(jsonInTree);//using the tree implementation
    }
}

JSONComparator

class JSONComparator implements Comparator<JSONObject> {
    private String fieldToCompare;

    public JSONComparator(String fieldToCompare) {
        this.fieldToCompare = fieldToCompare;
    }

    @Override
    public int compare(JSONObject o1, JSONObject o2) {
        String id1 = "";
        String id2 = "";
        try {
            id1 = o1.getString(this.fieldToCompare);
            id2 = o2.getString(this.fieldToCompare);
        } catch (JSONException e) {

        }

        return id1.compareTo(id2);
    }
}

做這種事情的最簡單方法將適用於所有不可比較的類。 您可以通過創建自己的比較方法來做到這一點,您可以采用以下方式:

public static int compareJSONObjects(JSONObject obj1, JSONObject obj2){
    if(obj1.getField()>obj2.getField()){
        return 1;
    }else{
        return -1;
    }
}

現在,當您調用list.sort()時,可以創建自己的Comparator,如下所示:

list.sort( (obj1, obj2) -> compareJSONObject(obj1, obj2) );

通過這樣做,您減少了所需的行數,因為通過使用三元並執行以下操作,整個事情可以縮短為1行:

list.sort( (obj1, obj2) -> obj1.getField()>obj2.getField() ? 1 : -1 );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM