[英]Compare values of <Key, Value> Pairs and sort them
I have Pairs that I would like to sort.我有要排序的对。 I have already done the compare implementation and it seems to be working.
我已经完成了比较实现,它似乎正在工作。
I also saw a solution online but the problem is that it doesn't allow it to be static.我也在网上看到了一个解决方案,但问题是它不允许它是静态的。
public static ArrayList <Pair<Integer, Integer>> pairList = new ArrayList<Pair<Integer, Integer>>();
public static Pair<Integer, Integer> pair1 = new Pair<>(6, 7);
public static Pair<Integer, Integer> pair2 = new Pair<>(7, 7)
This is where I'm getting the Error Change compare() to static
with the solution that I'm testing out.这是我使用我正在测试的解决方案将 Error
Change compare() to static
的地方。
Method that I'm testing out:我正在测试的方法:
public class MachineNoComparator implements Comparator <Pair<Integer, Integer>> {
public int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
return o1.getMachineNo().compareTo(o2.getMachineNo());
}
}
You probably call compare as您可能将比较称为
compare(pair1,pair2);
pair1 and pair2 are static and compare not. pair1 和 pair2 是静态的,比较不是。 When you pass static fields to a function, the function also has to be static.
当您将静态字段传递给函数时,该函数也必须是静态的。 This is the reason of why you take this error.
这就是你为什么会犯这个错误的原因。
You can solve this by changing compare method to;您可以通过将比较方法更改为;
public static int compare(Pair<Integer, Integer> o1, Pair<Integer, Integer> o2) {
return o1.getMachineNo().compareTo(o2.getMachineNo());
}
or fields to;或字段;
public Pair<Integer, Integer> pair1 = new Pair<>(6, 7);
public Pair<Integer, Integer> pair2 = new Pair<>(7, 7);
But you should have a look what 'static' keyword is and what it does.但是您应该看看“静态”关键字是什么以及它的作用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.