简体   繁体   English

如果元组是一个预定义的类而没有Java中的实现比较器,则如何对元组数组进行排序

[英]How to sort a array of tuple if the tuple is a pre-defined class without implement comparator in Java

I have a pre-defined tuple class which cannot be modified as follows: 我有一个预定义的元组类,无法将其修改如下:

public class Tuple {
    protected String name; 
    public Tuple(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

I have another class which defines an array of the above tuple: 我有另一个类,它定义上述元组的数组:

public class Stack {
    protected ArrayList<Tuple> tupleLst; 
    public Stack(){
        this.tupleLst=new ArrayList<Tuple>(10);
    }
}

Then I need to sort the array of tuple in another class: for instance: 然后我需要在另一个类中对元组数组进行排序:例如:

public class Algo {
    public static int Sort(Relation r){

    }
    public static void main(String[] arg){
    Algo.Sort();
}

The Relation r is the input array of tuples. 关系r是元组的输入数组。 I have searched online, where I saw many people actually are using Comparators and Collections.sort() to do that. 我在网上搜索过,在那里我看到很多人实际上正在使用Comparators和Collections.sort()来做到这一点。 However, after I tried, I noticed that the Tuple class need to implement comparators in order to sort. 但是,在尝试之后,我注意到Tuple类需要实现比较器才能进行排序。 How can I sort the tuple without changing the first two classes? 如何在不更改前两个类的情况下对元组进行排序? Thank you in advance! 先感谢您!

Although Tuple cannot be modified, you can implement a Comparator of your own and then pass it to the Collections.sort() method (which will do a sort of your collection of tuples based on the comparator rule(s). For example: 尽管无法修改Tuple ,但是您可以实现自己的Comparator ,然后将其传递给Collections.sort()方法(该方法将根据比较器规则对元组进行某种排序。例如:

Comparator<Tuple> myComparator = new Comparator<Tuple>() {
    public int compare(Tuple t1, Tuple t2) {
        //the comparison rules go here
    }
};
Collections.sort(tupleList, myComparator);

If you use Java8, you can achieve this in a single line: 如果使用Java8,则可以单行实现:

myList.sort((t1, t2) -> { <comparison rules implementation> });

or (thanks to @MarkoTopolnik) 或(由于@MarkoTopolnik)

myList.sort(Comparator.comparing(t -> <<get sort key from t>>) 

I think you're confusing two methods. 我认为您在混淆两种方法。 One way is to make your Tuple class implement the Comparable interface. 一种方法是使您的Tuple类实现Comparable接口。 I think this is the one you want to avoid since it seems you don't want to modify the Tuple class. 我认为这是您要避免的一种,因为您似乎不想修改Tuple类。

The other way is to define a new class, whose purpose is to compare two Tuples. 另一种方法是定义一个新类,其目的是比较两个元组。 This is what is called a Comparator. 这就是所谓的比较器。 If you pass your list of Tuples and an instance of this comparator then you can sort your Tuples any way you like without modifying the Tuple class. 如果传递了元组列表和此比较器的实例,则可以在不修改元组类的情况下以任意方式对元组进行排序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM