-3

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.

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());
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Gana
  • 75
  • 1
  • 7

1 Answers1

-1

You probably call compare as

compare(pair1,pair2);

pair1 and pair2 are static and compare not. 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.

xxlali
  • 996
  • 2
  • 15
  • 43