1
4

2 に答える 2

1

高階関数のようなにおいがするものを使用できます。つまり、Longからint(優先度)またはデータまでの種類のマップを取得し、新しいコンパレータを返す静的関数を作成します。

getComparatorクラスFooには、Orangeを受け取る静的メソッドがあります。getPriorityOrangeは、IDを受け取り、対応する優先度を返すメソッドを持つクラスです。このgetComparatorメソッドは、新しいComparatorオブジェクトを作成します。新しいComparatorオブジェクトのcompareメソッドは2つのIDを取ります。2つのIDの対応する優先度を検索し、それらを比較します。

public interface Orange {
    // Looks up id and returns the corresponding Priority.
    public int getPriority(Long id);
}

public class Foo {
    public static Comparator<Long> getComparator(final Orange orange) {
        return new Comparator<Long>() {
            public int compare(Long id1, Long id2) {
                // Get priority through orange, or
                // Make orange juice from our orange.
                // You may want to compare them in a different way.
                return orange.getPriority(id1) - orange.getPriority(id2);
        };
    }
}

私のJavaは少し錆びているので、コードに欠陥がある可能性があります。ただし、一般的な考え方は機能するはずです。

使用法:

// This is defined somewhere. It could be a local variable or an instance
// field or whatever. There's no exception (except is has to be in scope).
Collection c = ...;
...
Orange orange = new Orange() {
    public int getPriority(Long id) {
        // Insert code that searches c.mySet for an instance of data
        // with the desired ID and return its Priority
    }
};
Collections.sort(c.myList, Foo.getComparator(orange));

オレンジがどのように見えるかについての例は示していません。

于 2012-10-10T11:11:42.373 に答える
0

I assume that you have a List<Data> stored somewhere.. In Comparator, you need to invoke a getDataById method from your data class, and sort through Priority..

Check the below code.. I have used a single class for many purpose..

Ideally you would want to break it into more classes.. But this is just a Demo, how to achieve what you want..

class Container {
    // List of Data  instances created..
    // This list has to be static, as it is for a class, 
    // and not `instance specific`
    public static List<Data> dataList = new ArrayList<Data>();

    // List of Ids, that you want to sort.
    private List<Long> idList = new ArrayList<Long>();

    // Populate both the list..

    // Have a method that will iterate through static list to 
    // find Data instance for a particular id

    public static Data getDataById(long id) {
        // Find Data with id from the list

        // Return Data
    }

    public void sortList() {
        Collections.sort(idList, new MyComparator());
    }
}

public MyComparator implements Comparator<Long> {

    public int compare(Long int1, Long int2) {
        Data data1 = Container.getDataById(int1);
        Data data2 = Container.getDataById(int2);

        return data1.getPriority() - data2.getPriority();
    }
}
于 2012-10-10T11:03:26.480 に答える