ClassCastException when casting Object[] array to generic type array in Java

那年仲夏 提交于 2020-01-17 05:18:06

问题


Hi I'm very new to Java and in this code, I think I'm not creating the Bag correctly in the Main? Please help thanks!

Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Comparable; at mid.Bag.(Bag.java:12) at mid.Bag.main(Bag.java:91)

        public class Bag<T extends Comparable<T>> implements Iterable<T> {
      private int MAX_ITEMS = 10; // initial array size
      private int size;
      private T[] data;

      public Bag( ) {
        data = (T []) new Object[MAX_ITEMS];
        size = 0;
      }

      public void add(T newItem) {
        // check if it's full, then extend (array resizing)
        if (size == data.length) {
          T[ ] temp = (T [ ] ) new Object[data.length*2];
          for (int i = 0; i < size; ++i)
            temp[i] = data[i];
          // reassign data to point to temp
          data = temp;
        }
        // then do the assignment
        data[size++] = newItem; // assign newItem in the next-available slot
      }

public Iterator<T> iterator() {
    return new BagIterator();
  }

 /***************************
  * nested class BagIterator
  ***************************/
   class BagIterator implements Iterator<T> {
    // instance member
    private int index;

    // (0) constructor
    public BagIterator() {
      index = 0;
    }
    // (1)
    public boolean hasNext() {
      return (index < size); // size in the outer Bag<E>
    }
    // (2)
    public T next() {
      /*
      T temp = data[index]; // save the element value
      index++; // increment index
      return temp;
      */
      return data[index++];
    }
      public static void main(String[ ] args) {
          Bag<String> bag1=new Bag<String>();

          bag1.add("good");
          bag1.add("fortune");
          bag1.add("billionarie");
          for (String x: bag1)
              System.out.println(x);

      }

回答1:


Yes, you're creating an Object[] and then trying to cast it to T[], which the compiler is converting to a cast to Comparable[] (using the raw Comparable type) due to your constraint on T.

Arrays and generics don't work terribly nicely together, basically.

It would probably be simpler to make your data field just an Object[] and cast individual values where necessary.




回答2:


Here:

data = (T []) new Object[MAX_ITEMS];

you are constructing an Object array and trying to cast it to T[]. But you have declared that T inherits from Comparable. So use:

data = (T []) new Comparable[MAX_ITEMS];



回答3:


You can probably rewrite your constructor as well:

public Bag(Class<T> c, int s) {
    // Use Array native method to create array of a type only known at run time
    @SuppressWarnings("unchecked")
    final T[] dataArray = (T[]) Array.newInstance(c, s);
    this.data = dataArray;
}

Then you can use it like:

Bag<String> bag1 = new Bag<>(String.class,10);

That should also work, IMO. The instances of T must be comparable in any case.



来源:https://stackoverflow.com/questions/30096690/classcastexception-when-casting-object-array-to-generic-type-array-in-java

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