Ramesh Manian
Ramesh Manian

Reputation: 1

Error creating and casting an array of objects

I am trying to create an iterator in which I am creating an array of objects. I have to type cast them as Generics array creation is disallowed.

I am getting a run time error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [LRandomizedQueueList$Node;

The full code of the iterator is shown below. I don't know what I am doing wrong.

   private class RandomizedQueueIterator implements Iterator<Item> {
       private Node current = first;
       private Node[] ca = (Node[])new Object[size()];
       //private Node[] ca = new Node[size()];

       private RandomizedQueueIterator() {
           if (first == null) throw new NoSuchElementException();
           for (int j = 0; j < size(); j++) {
               ca[j] = current;
               current = current.next;
           }                        
           StdRandom.shuffle(ca);
           current = ca[0];
       }

       public boolean hasNext()  { return current != null; }

       public Item next() {
           if (current == null) throw new NoSuchElementException();
           Item item = current.item;
           current = current.next; 
           return item;
       }
       public void remove() {
           throw new UnsupportedOperationException("This method is not supported");
       }
   } 

I appreciate any help in understanding this error.

Upvotes: 0

Views: 51

Answers (2)

JB Nizet
JB Nizet

Reputation: 691715

The exception is clear: you can't cast an Object[] to Node[]. Object[] is not a subclass of Node[].

Replace the code by

private Node[] ca = new Node[size()];

Upvotes: 1

BobTheBuilder
BobTheBuilder

Reputation: 19284

Use:

private Node[] ca = new Node[size()];

There is no need to cast the array when you create it. You can just create an array of Node.

Upvotes: 1

Related Questions