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

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);

      }
Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow