错误消息:类型Collections中的方法sort(List< T>)不适用于参数(ArrayList< Date>) [英] Error Message: The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Date>)

查看:464
本文介绍了错误消息:类型Collections中的方法sort(List< T>)不适用于参数(ArrayList< Date>)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

继续收到错误消息,但不知道为什么。无法使用Collections.sort()

Keep getting error message, but don't know why. Can't get code to sort the list using Collections.sort()

获得代码对列表进行排序,这就是我所拥有的。 3个Java文件。

Here is what I have. 3 java files.

接口文件。

public interface Comparable<T> {
   public int compareTo(T other);
}

Class文件。

public class Date implements Comparable<Date>{

private int year;
private int month;
private int day;

public Date(int month, int day, int year){   
   this.month = month;
   this.day = day;
   this.year = year;
}

public int getYear(){
   return this.year;
}

public int getMonth(){
   return this.month;
}

public int getDay(){
   return this.day;
}
public String toString(){
   return month + "/" + day + "/" + year;
}


public int compareTo(Date other){
    if (this.year!=other.year){
        return this.year-other.year;
    } else if (this.month != other.month){
        return this.month-other.month;
    } else {
        return this.day-other.day;
    }
}

}

Client类

import java.util.*;

public class DateTest{
   public static void main(String[] args){

  ArrayList<Date> dates = new ArrayList<Date>();
  dates.add(new Date(4, 13, 1743)); //Jefferson
  dates.add(new Date(2, 22, 1732)); //Washington
  dates.add(new Date(3, 16, 1751)); //Madison
  dates.add(new Date(10, 30, 1735)); //Adams
  dates.add(new Date(4, 28, 1758)); //Monroe     


  System.out.println(dates);
  Collections.sort(dates);
  System.out.println("birthdays = "+dates);

}




}

我得到的错误消息是 Collections类型中的方法sort(List)不适用于参数(ArrayList)

The error message I get is "The method sort(List) in the type Collections is not applicable for the arguments (ArrayList)"

推荐答案

因为 Collections.sort 期望 java.lang.Comparable 而不是您的可比较的接口,更改您的 Date 类以实现 java.lang.Comparable

Because Collections.sort expects java.lang.Comparable and not your Comparable interface, change your Date class to implement the java.lang.Comparable.

public class Date implements java.lang.Comparable<Date>{
 ..
}

如果出于某些原因仍想定义自己的Comparable,并且仍要使用Collections.sort,则您的 Comparable 必须是 java.util.Comparable

If you still want to define your own Comparable for some reasons and you still want to use Collections.sort then the your Comparable has to be java.util.Comparable

interface Comparable<T> extends java.lang.Comparable<T> {

}

这篇关于错误消息:类型Collections中的方法sort(List&lt; T&gt;)不适用于参数(ArrayList&lt; Date&gt;)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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