Collections.sort()错误 [英] Collections.sort() error

查看:1462
本文介绍了Collections.sort()错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试根据Class A的int r对B类中名为BinOrder的A类型的列表进行排序。

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

但是我收到了该行集合的错误.sort(BinOrder);

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>)

A类:

public class A{
int s; 
int r;

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

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;
    }
}


推荐答案

到能够使用 Collection.sort() ArrayList A A 应该实现 Comparable 界面:

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) {
    ...
  }
}

这篇关于Collections.sort()错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆