简体   繁体   English

java.lang.Object; 无法转换为[java.lang.comparable]

[英]java.lang.Object; cannot be cast to [java.lang.comparable]

I'm stuck at this java.lang.ClassException . 我被困在这个java.lang.ClassException In general, I'm trying with a simple method maxElement() that simply returns the highest Integer, the add() method works perfectly as well as overriding toString() , this last 2 methods are inherited from ArrayLinearList<T> . 总的来说,我正在尝试一个简单的方法maxElement() ,该方法仅返回最高的Integer, add()方法也可以很好地工作并覆盖toString() ,后两个方法是从ArrayLinearList<T>继承的。 element is an array . 元素是一个数组。 ArrayLinearList does work perfectly as well .This is my code: ArrayLinearList也可以很好地工作。这是我的代码:

public class ArrayLinearList<T> implements LinearList<T>, Iterable<T>{
 protected T[] element; 
 protected int size; 
  *constructors and methods*
  // default constructor makes an T[]element of length 10

} }

public class ArrayLinearListTaller1<T extends  Comparable<T>> extends ArrayLinearList<T>{
  public static void main(String[] args) {
    ArrayLinearListTaller1<Integer>x=new ArrayLinearListTaller1<Integer>();
    x.add(0, new Integer(10));
    x.add(1, new Integer(5));
    x.add(2, new Integer(7));
    System.out.println(x);
    System.out.println(x.maxElement());
    }// end of main

 public T maxElement() {
    Arrays.sort(element,0,size);
    T max= element[size-1];//*error here*
    return max;
}

This is what I get: 这是我得到的:

[10,5,7]  
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;

The elements passed to Arrays.sort() must implement Comparable interface. 传递给Arrays.sort()的元素必须实现Comparable接口。

Sorts the specified range of the specified array of objects into ascending order, according to the natural ordering of its elements. 根据其对象的自然顺序,将指定对象数组的指定范围按升序排序。 The range to be sorted extends from index fromIndex, inclusive, to index toIndex, exclusive. 要排序的范围从索引fromIndex(含)到索引toIndex(不包含)。 (If fromIndex==toIndex, the range to be sorted is empty.) (如果fromIndex == toIndex,则要排序的范围为空。)

All elements in this range must implement the Comparable interface. 此范围内的所有元素都必须实现Comparable接口。

Furthermore, all elements in this range must be mutually comparable (that is, e1.compareTo(e2) must not throw a ClassCastException for any elements e1 and e2 in the array). 此外,此范围内的所有元素都必须相互可比较(即e1.compareTo(e2)不得对数组中的任何元素e1和e2抛出ClassCastException)。

So the Objects present in element array must implement Comparable interface . 因此, element数组中存在的对象必须实现Comparable接口

It seems to me like whatever your type of object for element is does not implement Comparable interface and you're getting exception from Arrays.sort(). 在我看来,无论您的元素对象类型是什么,都不实现Comparable接口,并且您从Arrays.sort()中获取异常。 Maybe sharing your full code will help. 也许共享您的完整代码会有所帮助。

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

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