【问题标题】:Error Message: The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Date>)错误消息:集合类型中的方法 sort(List<T>) 不适用于参数 (ArrayList<Date>)
【发布时间】:2016-06-11 20:13:33
【问题描述】:

不断收到错误消息,但不知道为什么。无法获取代码以使用 Collections.sort() 对列表进行排序

这就是我所拥有的。 3 个 java 文件。

接口文件。

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

类文件。

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

}

客户端类

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

}




}

我得到的错误信息是“集合类型中的方法 sort(List) 不适用于参数 (ArrayList)”

【问题讨论】:

    标签: java collections interface


    【解决方案1】:

    因为 Collections.sort 需要 java.lang.Comparable 而不是您的 Comparable 接口,请更改您的 Date 类以实现 java.lang.Comparable

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

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

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

    【讨论】:

    • java.util.Comparable ? java.lang.comparable 对吗?
    【解决方案2】:

    你的问题是

    import java.util.*;
    

    你也导入了java.util.DateDate 因此是矛盾的:)

    【讨论】:

      猜你喜欢
      • 2020-12-31
      • 1970-01-01
      • 1970-01-01
      • 2013-08-20
      • 2013-03-20
      • 1970-01-01
      • 2018-04-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多