我正在尝试实现一个通用的 Bag 类,它可以计算包中大于对象 x 的对象数量,为此我使用 Date 类来测试它。
包码:
class Bag<T extends Comparable<T>>
{// generic class with T standing for a class
private T[] bag = (T[])(new Object[100]);
private int numElements = 0; // junk in bag[numElements..]
void add(T x)
{ // put x in bag
bag[numElements] = x; numElements++;
}
int freq(T x)
{ // how many x’s in bag?
int count = 0;
for (int i=0; i<numElements; i++)
if (bag[i].equals(x)) // .equals because T a class
count++;
return count;
}
int numGreater(T x)
{//number of objects greater than x
int greaterThan = 0;
for(int i = 0; i<= bag.length; i++)
{
if(bag[i].compareTo(x) == 1)
{
greaterThan++;
}
}
return greaterThan;
}
}
日期代码:
import java.util.*;
import java.lang.*;
class Date implements Comparable<Date>
{ // dates
private int day, month, year;
Date(int day0, int month0, int year0)
{
day = day0; month = month0; year = year0;
}
public String toString()
{
return "" + day + "/" + month + "/" + year;
}
private int elapsedDays()
{
// Number of days elapsed from 1/1/1900 to this date
int days = (year-1900)*365+(year-1901)/4;
int k = 1;
while (k<month)
{
int daysInMonth;
if (k==9||k==4||k==6||k==11)daysInMonth = 30;
else if (k==2)
{
if (year%4==0 && year!=1900) daysInMonth = 29;
else daysInMonth = 28;
}
else daysInMonth = 31;
days = days + daysInMonth;
k++;
}
return days + day;
}
public int compareTo(Date d)
{
if(d.elapsedDays() > elapsedDays())
{
return -1;
}
if(d.elapsedDays() == elapsedDays())
{
return 0;
}
return 1;
}
}
最后是我正在使用的测试程序:
import java.util.*;
import java.lang.*;
class BagTest
{
public static void main(String[] args)
{//finds dates greater than today
Bag<Date> ds = new Bag<>();
Date today = new Date(07,11,2013);
Date d1 = new Date(1,11,2013);
Date d2 = new Date(8,11,2013);
Date d3 = new Date(9,11,2013);
ds.add(today);
ds.add(d1);
ds.add(d2);
ds.add(d3);
System.out.print(ds.numGreater(today));
}
}
我收到的错误消息如下:
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; can
not be cast to [Ljava.lang.Comparable;
at Bag.<init>(Bag.java:6)
at BagTest.main(BagTest.java:8)
提前感谢您的帮助!