我的比较器应该是什么类型

时间:2015-12-25 13:46:08

标签: java comparator

我希望根据条目值中的整数进行比较List

List<Map.Entry<OfficerRank, Integer>> lst = new ArrayList<Map.Entry<OfficerRank, Integer>>();
lst.addAll(mp.entrySet());
Collections.sort(lst,new CompareRank<Map.Entry<OfficerRank, Integer>>());

那是我的比较代码:

public class CompareRank<Map.Entry<OfficerRank,Integer>> implements Comparator<Map.Entry<OfficerRank, Integer>>{
  @Override
  public int compare(Map.Entry<OfficerRank,Integer> arg0, Map.Entry<OfficerRank,Integer> arg1) {
    int val1 = arg0.getValue();
    int val2 = arg1.getValue();
    return Integer.compare(val2,val1);
  }

我的问题是我不能使用Map.Entry<OfficerRank,Integer>作为Eclipse的类型

谢谢

3 个答案:

答案 0 :(得分:0)

请同样使用:

public class CompareRank implements Comparator<Map.Entry<Integer, Integer>>{

    @Override
    public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
        // TODO Auto-generated method stub
        return 0;
    }
}

在这里,为了方便,我采取了Entry<Integer, Integer>,

但你可以继续Entry<YOURCLASSTYPE, Integer>

答案 1 :(得分:0)

正如你现在所知,let captureDevice = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) let input = try! AVCaptureDeviceInput(device: captureDevice) captureSession.addInput(input) captureSession.sessionPreset = AVCaptureSessionPresetPhoto let stillImageOutput = AVCaptureStillImageOutput() captureSession.addOutput(stillImageOutput) captureSession.startRunning() let connection = stillImageOutput.connectionWithMediaType(AVMediaTypeVideo) stillImageOutput.captureStillImageAsynchronouslyFromConnection(connection) { (sampleBuffer, error) in print("maximum quality photo: \(sampleBuffer)\n") } 的类型参数是别名,而不是实际类型。

您不必为CompareRank类定义类型参数,只需指出CompareRank必须处理的实际类型:

Comparator

然后,你应该像这样实例化它:

import static java.util.Map.Entry;

public class CompareRank implements Comparator<Entry<OfficerRank, Integer>>{
  @Override
  public int compare(Entry<OfficerRank,Integer> arg0, Entry<OfficerRank,Integer> arg1) {
    int val1 = arg0.getValue();
    int val2 = arg1.getValue();
    return Integer.compare(val2,val1);
}

答案 2 :(得分:0)

也许你在这里使用错误的Map.Entry。如果你想将它用作元组,最好定义一个帮助器“元组”类:

public class Tuple<T1,T2> {
   // etc...
}

并将其实例化为:

Tuple<OfficeRank,Integer> entry = ...

或者更好的是,一个封装OfficeRank和Integer的类,在您的问题域中具有一些语义含义。

public class OfficeRankValue {
    Integer whateverTheIntegerIs;
    OfficeRank officeRank;
}