5

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)
Shiladittya Chakraborty
  • 3,982
  • 7
  • 35
  • 74
szufi
  • 189
  • 1
  • 7

2 Answers2

9

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.

Clashsoft
  • 10,343
  • 4
  • 37
  • 68
1

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");
}
Zhedar
  • 3,290
  • 1
  • 19
  • 41
Hovercraft Full Of Eels
  • 276,051
  • 23
  • 238
  • 346
  • that code will produce just the same error as the above code. the error is thrown in the constructor. `(T[]) new Object[startSize];` won't magically turn an `Object[]` into a `T[]`. Please remove the answer or correct it. – Paul Jan 16 '16 at 13:45
  • Yes, still the same :/ – szufi Jan 16 '16 at 13:48
  • @szufi search for sth like "generic array creation". I've already marked the question duplicate, just have a look at the post I've selected as dup. – Paul Jan 16 '16 at 13:49
  • 3
    How did an answer that is **that** fundamentally wrong even get a single upvote? – Paul Jan 16 '16 at 14:34