静态方法如何使用比较器?

时间:2022-09-04 10:59:49

I have a static method which needs to invoke the SportsMenComparator. But this, as we all know is not allowed. How does a static function use a comparator subclass ? Although I have workarounds, I am looking for best practices for this particular problem.

我有一个静态方法,需要调用SportsMenComparator。但我们都知道这是不允许的。静态函数如何使用comparator子类?虽然我有变通方法,但我正在寻找这个特殊问题的最佳实践。

final class SportsMan {

    private final String name;
    private final int rank;
    private final String sport;

    public SportsMan (String name, int rank, String sport)  {
        this.name = name;
        this.rank = rank;
        this.sport = sport;
    }

    public String getName() {
        return name;
    }

    public int getRank() {
        return rank;
    }

    public String getSport() {
        return sport;
    }
}


final class Sport {

    private final String sport;
    private final int numberOfPlayers;

    public Sport(String sport, int numberOfPlayers) {
        this.sport = sport;
        this.numberOfPlayers = numberOfPlayers;
    }

    public String getSport()  {
        return sport;
    }

    public int getNumberOfPlayers() {
        return numberOfPlayers;
    }
}


public final class Joins {

    private Joins () {}



    public class SportsMenComparator implements Comparator<SportsMan> {
        @Override
        public int compare(SportsMan s1, SportsMan s2) {
            return s1.getSport().compareTo(s2.getSport());
        }
     }



    public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList) {
        Collections.sort(sportsMans, new SportsMenComparator());

    }


}

Eclipse results in the following message: No enclosing instance of type Joins is accessible where Joins is name of the enclosing class.

Eclipse会产生以下消息:join是封闭类的名称,所以不可以访问类型连接的封闭实例。

5 个解决方案

#1


3  

But this, as we all know is not allowed. How does a static function use a comparator subclass ?

但我们都知道这是不允许的。静态函数如何使用comparator子类?

You cannot use a non static reference,still you are allowed to create a new object and use it. So since you are creating a new SportsMenComparator object and passing, no issues.

您不能使用非静态引用,仍然可以创建一个新对象并使用它。因此,由于您正在创建一个新的SportsMenComparator对象和传递,所以没有问题。

For example:

例如:

public static void main(String[] args) {
            List<String> s =new ArrayList<String>();
            s.add(""); // allowed
        }

But

List<String> s =new ArrayList<String>();
        public static void main(String[] args) {
            System.out.println();
            s.add(""); // Error: Cannot make a static reference to the non-static field s
        }

Edit:

编辑:

Since you defined the comparator class inside the Joins , you need the Joins object to access the comparation inside it

因为您在连接中定义了comparator类,所以您需要连接对象来访问它内部的比较。

Collections.sort(sportsMans, new Joins().new SportsMenComparator());

#2


1  

For using a Comparator, there is no difference between using it from a static- or non-static method. In either case an instance of the Comparator has to be used.

对于使用比较器,使用静态或非静态方法是没有区别的。在这两种情况下,都必须使用比较器的实例。

The Garbage Collector of modern JVMs is very efficient at handling short-lived objects. Therefore the penalty to be paid for using a fresh instance (via new) every time is usually no issue. However, if you don't want to use a fresh instance every time, I think the best option would be to add a static field to your SportsMenComparator, containing a singleton instance of the comparator:

现代jvm的垃圾收集器在处理短时间对象时非常有效。因此,每次使用一个新实例(通过新实例)的代价通常是没有问题的。但是,如果您不想每次都使用一个新的实例,我认为最好的选择是将静态字段添加到您的SportsMenComparator中,其中包含比较器的单例实例:

public class SportsMenComparator implements Comparator<SportsMan> {
  public static final SportsMenComparator instance=new SportsMenComparator();
  @Override
  public int compare(SportsMan s1, SportsMan s2) {
    return s1.getSport().compareTo(s2.getSport());
  }
}

public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList) {
  Collections.sort(sportsMans, SportsMenComparator.instance);
}

#3


1  

The problem is that you try to access an instance element (in this case it is a class, indeed the same as with a filed or method) within a static method, which is not associated with an instance. SURESH ATTA's answer is right, but you can also make your SportsMenComparator class static and it will work. I do not sse any reason to associate your comparator with an instance of the Joins class.

问题是,您试图访问一个实例元素(在本例中它是一个类,实际上与在静态方法中使用一个归档或方法相同),而静态方法与实例没有关联。SURESH ATTA的回答是正确的,但是你也可以让你的SportsMenComparator类保持静态,它也会起作用。我没有任何理由将您的比较器与联接类的实例相关联。

#4


0  

One can use something like this---

你可以用这样的东西。

public static boolean someMethod(MyObject obj1, MyObject obj2){
    return obj1.compare(obj2);
}

#5


0  

Why you cant include parameter to the function.

为什么不能将参数包含到函数中。

public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList, Comparator comparator) {
    Collections.sort(sportsMans, comparator);
}

#1


3  

But this, as we all know is not allowed. How does a static function use a comparator subclass ?

但我们都知道这是不允许的。静态函数如何使用comparator子类?

You cannot use a non static reference,still you are allowed to create a new object and use it. So since you are creating a new SportsMenComparator object and passing, no issues.

您不能使用非静态引用,仍然可以创建一个新对象并使用它。因此,由于您正在创建一个新的SportsMenComparator对象和传递,所以没有问题。

For example:

例如:

public static void main(String[] args) {
            List<String> s =new ArrayList<String>();
            s.add(""); // allowed
        }

But

List<String> s =new ArrayList<String>();
        public static void main(String[] args) {
            System.out.println();
            s.add(""); // Error: Cannot make a static reference to the non-static field s
        }

Edit:

编辑:

Since you defined the comparator class inside the Joins , you need the Joins object to access the comparation inside it

因为您在连接中定义了comparator类,所以您需要连接对象来访问它内部的比较。

Collections.sort(sportsMans, new Joins().new SportsMenComparator());

#2


1  

For using a Comparator, there is no difference between using it from a static- or non-static method. In either case an instance of the Comparator has to be used.

对于使用比较器,使用静态或非静态方法是没有区别的。在这两种情况下,都必须使用比较器的实例。

The Garbage Collector of modern JVMs is very efficient at handling short-lived objects. Therefore the penalty to be paid for using a fresh instance (via new) every time is usually no issue. However, if you don't want to use a fresh instance every time, I think the best option would be to add a static field to your SportsMenComparator, containing a singleton instance of the comparator:

现代jvm的垃圾收集器在处理短时间对象时非常有效。因此,每次使用一个新实例(通过新实例)的代价通常是没有问题的。但是,如果您不想每次都使用一个新的实例,我认为最好的选择是将静态字段添加到您的SportsMenComparator中,其中包含比较器的单例实例:

public class SportsMenComparator implements Comparator<SportsMan> {
  public static final SportsMenComparator instance=new SportsMenComparator();
  @Override
  public int compare(SportsMan s1, SportsMan s2) {
    return s1.getSport().compareTo(s2.getSport());
  }
}

public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList) {
  Collections.sort(sportsMans, SportsMenComparator.instance);
}

#3


1  

The problem is that you try to access an instance element (in this case it is a class, indeed the same as with a filed or method) within a static method, which is not associated with an instance. SURESH ATTA's answer is right, but you can also make your SportsMenComparator class static and it will work. I do not sse any reason to associate your comparator with an instance of the Joins class.

问题是,您试图访问一个实例元素(在本例中它是一个类,实际上与在静态方法中使用一个归档或方法相同),而静态方法与实例没有关联。SURESH ATTA的回答是正确的,但是你也可以让你的SportsMenComparator类保持静态,它也会起作用。我没有任何理由将您的比较器与联接类的实例相关联。

#4


0  

One can use something like this---

你可以用这样的东西。

public static boolean someMethod(MyObject obj1, MyObject obj2){
    return obj1.compare(obj2);
}

#5


0  

Why you cant include parameter to the function.

为什么不能将参数包含到函数中。

public static void innerJoinSort(List<SportsMan> sportsMans, List<Sport> sportList, Comparator comparator) {
    Collections.sort(sportsMans, comparator);
}