Collections.sort() error

倖福魔咒の 提交于 2019-12-02 14:08:25

问题


I am trying to sort a list of type A named BinOrder in class B according to Class A's int r.

However i am receiving this error for the line Collections.sort(BinOrder);

The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<A>)

Class A:

public class A{
int s; 
int r;

public A(int si, int ri) {
    s=si;
    r= ri;
 }
}

Class B:

import java.util.ArrayList;
import java.util.Collections;


public class B implements Comparable<A> {



    public Iterator<A> randomMethodName(int a) {
        ArrayList<A> BinOrder = new ArrayList<A>();
                A a = new A(1,3)
                A a2 = new A(1,4)

                BinOrder.add(a);
                BinOrder.add(a2);
        }

        // sort array in increasing order of r
        Collections.sort(BinOrder);
        return BinOrder;
    }

    @Override
    public int compareTo(A list) {

        return null;
    }
}

回答1:


To be able to use the single-argument version of Collection.sort() on an ArrayList of A, A should implement the Comparable interface:

public class A implements Comparable<A> {
  ...
  @Override
  int compareTo(A rhs) {
    ...
  }
}



回答2:


Here's the signature of Collections.sort :

public static <T extends Comparable<? super T>> void sort(List<T> list)

A must implement Comparable for this method.

You try to pass BinOrder to this method, when BinOrder is of type ArrayList<A>, but since A does not implement Comparable<A>, it doesn't fit the signature of the method.

Either change A to implement Comparable, or use the sort method that accepts a Comparator :

public static <T> void sort(List<T> list, Comparator<? super T> c)


来源:https://stackoverflow.com/questions/27473047/collections-sort-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!