Java怎么实现泛型数据的比较

 public class ArrayImplementation <Element> implements Iterable<Element>{
    private Element [] list;

    public ArrayImplementation (final int initSize)
    {
        list = (Element[]) new Object[initSize];
        this.size = initSize;
    }

    private boolean increaseSorted()
    {
        for (int i=1;i<length;i++)
        {
            if (list[i].compareTo(list[i-1])<0)
            {
                return false;
            }
        }
        return true;
    }
}

我如何让Element使用compareTo方法?

如果我写成

public class ArrayImplementation <Element extends Comparable> implements Iterable<Element>{
    public ArrayImplementation (final int initSize)
    {
        list = (Element[]) new Object[initSize];
        this.size = initSize;
    }
        private boolean increaseSorted()
    {
        for (int i=1;i<length;i++)
        {
            if (list[i].compareTo(list[i-1])<0)
            {
                return false;
            }
        }
        return true;
    }

 }

让Element继承Comparable,就会报错

 Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

我要怎么写呢?

compareTo()是按字典顺序比较两个字符串,你直接用于比较元素对象是肯定不行的。你比较的应该是某个属性值。参考一下这个:http://bbs.csdn.net/topics/210063738

实现IComparable接口,实现compareTo方法

从IComparable继承,实现compareTo方法

你的问题其实不在泛型如何比较,而是在这句

 list = (Element[]) new Object[initSize];

这样的强转是不行的,因为泛型声明了
即Element是实现了Comparable接口的,那么Object无法强转为Element

自己实现Comparable,根据自己的业务编写比较方法!