繁体   English   中英

错误消息:方法排序(列表 <T> )类型集合不适用于参数(ArrayList <Date> )

[英]Error Message: The method sort(List<T>) in the type Collections is not applicable for the arguments (ArrayList<Date>)

继续收到错误消息,但不知道为什么。 无法使用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);

}




}

我得到的错误消息是“类型集合中的方法排序(列表)不适用于参数(ArrayList)”

因为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> {

}

你的问题在于

import java.util.*;

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM