0

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
  • You need to update your code for iterator() as the code does not compile. Commented May 7, 2015 at 9:32

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Hi Jon, thanks for your reply, is there a way to keep my field and adjust my bag type in the main?
@Robert, it would be nice to see your iterator() method to answer to this. Please add it to your question.
So you just need to use return (T)data[index++]; in your next() method and keep the data as Object[]. Your main method will not notice anything. Also it's easier to use ((List<T>)Arrays.asList(data)).iterator() instead of implementing your own iterator.
@Robert: I don't really know what you mean by that... and your response of "it's not working" to Tagir doesn't really give enough information to help you. I suspect you should create a new question for your ongoing problems - your initial question was about a ClassCastException, and that's now solved. Stack Overflow is geared towards one question per post - don't forget that we're trying to create a repository of information for future readers, not just solving all your problems.
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];

2 Comments

Hi khelwood, thanks for your reply, is there a way to keep my field and adjust my bag type in the main?
You can still keep your field. Just construct it as an array of Comparable instead of an array of Object. Or take out <T extends Comparable<T>> and replace it with <T>.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.