cannot be cast to [Ljava.lang.Comparable

天涯浪子 提交于 2020-06-12 08:44:06

问题


So I need to do dynamic ordered list.

    public class DynArrayListOrd<T extends Comparable<T>>  {
        private T[] tab ;

        public DynArrayListOrd()
        {
          tab = (T[])new Object[startSize];
        }
        ....

        main {
          DynArrayListOrd tab = new DynArrayListOrd();

          tab.add("John");
          tab.add("Steve");
        }

And when I run the code I get error:

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable;
    at structures.DynArrayListOrd.<init>(DynArrayListOrd.java:14)
    at structures.DynamicArrayAppp.main(DynArrayListOrd.java:119)

回答1:


The erased type of the T[] tab will be Comparable[]. Thus, you need to use this type in the constructor:

public DynArrayListOrd()
{
    tab = (T[]) new Comparable[startSize];
}

You should also enable unchecked warnings to avoid these kinds of problems in the first place.




回答2:


You're forgetting the generic parameter, <String>:

DynArrayListOrd<String> tab = new DynArrayListOrd<>();

Your code must be:

public class DynArrayListOrd<T extends Comparable<T>>  {
    private List<T> tab ;

public DynArrayListOrd()
{
    tab = new ArrayList<T>();
}
....

public static void main(String[] args){
    DynArrayListOrd<String> tab = new DynArrayListOrd<>();

    tab.tab.add("John");
    tab.tab.add("Steve");
}


来源:https://stackoverflow.com/questions/34827626/cannot-be-cast-to-ljava-lang-comparable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!