有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

将C++排序函数移植到java

<>我把C++代码移植到java上有问题。我有一个配对的清单如下

vector<pair<pair<int,int>,int> > M;

我用Java编写了如下等效代码

List<Pair<Pair<Integer,Integer>,Integer>> pairList = new ArrayList<>();
<>现在在C++代码中,M被填充了值,相应地,我在java中也这样做了。现在,C++具有如下的排序功能:

sort(M.begin(), M.end());

这是我的问题,我需要用Java编写的等效比较器是什么? 我如何使用它?我假设有以下几行

Collections.sort(pairList, new MyComparator())

有人能帮我理解什么是MyComparator吗

结对类如下

class Pair<K,V>{

    K k;
    V v;

    public void makePair(K k, V v){     
        this.k = k;
        this.v = v;
    }
}

解决方案

我最终实现了MyComparator,如下所示

static class MyComparator implements Comparator<Pair<Pair<Integer,Integer>,Integer>>{

    @Override
    public int compare(Pair<Pair<Integer,Integer>,Integer> p1,Pair<Pair<Integer,Integer>,Integer> p2){

        int a = p1.k.v.compareTo(p2.k.v);
        if(a==0) return a;
        else return p1.k.k.compareTo(p2.k.k);
    }
 }

谢谢大家


共 (3) 个答案

  1. # 1 楼答案

    <> p>可以通过使java ^ {< CD1>}类的行为类似C++ ^{}来避免比较。Apache Commons Lang有一个^{}可以满足您的需求

    但是:为什么不使用适当的自定义数据类而不是嵌套对呢?我已经认为C++版本相当麻烦。p>

    如果你不想使用它,请使用你自己的:

    class Pair<K extends Comparable<K>,V extends Comparable<V>>
       implements Comparable<Pair<K, V>> 
    {
       // have a immutable pairs
       final K k;
       final V v;
    
       Pair(final K k, final V v)
       {
           this.k = k;
           this.v = v;
       }
    
       // factory function, the same as in C++ 
       // (where it exists because template syntax is akward)
       // (as is generics syntax)
       public static <K extends Comparable<K>, V extends Comparable<V>> Pair<K, V> makePair(K k, V v)
       {     
             return new Pair(k, v);
       }
    
       @override
       public int compareTo(final Pair<K, V> other)
       {
            int compare = this.k.compareTo(other.k);
            if (compare == 0) {
                compare = this.v.compareTo(other.v);
            }
            return compare;
       }
    
       // NOTE: we also need equals() and hashCode() for a proper class.
    }
    

    我会尽量避免编写隐式Comparator,并将其传递给sort函数,除非您需要特殊的大小写排序

  2. # 2 楼答案

    比较器应该是一个实现接口Comparator<T>的类。T是与集合关联的泛型类型

    对你来说是Pair<Pair<Integer,Integer>,Integer>

    所以你应该上这样的课:

    public Class MyComparator implements Comparator<Pair<Pair<Integer,Integer>,Integer>> {
    
        @Override
        public int compare(Pair<Pair<Integer,Integer>,Integer> o1, Pair<Pair<Integer,Integer>,Integer> o2) {
            // Here you should put your comparison code :
            // return 0 if the 2 objects are the same
            // return -1 (or another negative int) if the o2 > o1
            // return 1 (or another positive int) if o2 < o1
    
        }
    
    }
    
  3. # 3 楼答案

    MyComparator需要实现^{},以便Java知道如何比较列表中的元素。它有两种形式Comparator^{}

    一个很好的例子是here