Search code examples
javacompareto

cannot be cast to [Ljava.lang.Comparable


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)

Solution

  • 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.