1

Class definition for Binary Search Tree in Java:

public class BST<E extends Comparable<E>> implements Iterable<E>, Cloneable
public Iterator<E> iterator() {
        return new BSTInOrderIterator();
    }

    private class BSTInOrderIterator implements Iterator<E> {
        private int sortedArrayFillerIndex;
        private final E[] sortedArray;

        private int ptr;

        public BSTInOrderIterator() {
            sortedArrayFillerIndex = 0;
            sortedArray = (E[]) (new Object[size()]);
            inOrder(root);
            ptr = 0;
        }

        private void inOrder(Node x) {
            if (x == null) return;
            inOrder(x.left);
            sortedArray[sortedArrayFillerIndex++] = x.value;
            inOrder(x.right);
        }

        @Override
        public boolean hasNext() {
            return ptr < size();
        }

        @Override
        public E next() {
            return sortedArray[ptr++];
        }
    }

In the iterator, I first build a sorted array through an inorder traversal of my BST. However, I get class cast exception in the constructor of the BST iterator. How do I handle that?

learner
  • 111
  • 9

1 Answers1

0

The issue is in the line sortedArray = (E[]) (new Object[size()]);. You cannot initialize a generic array like this. To initialize the sortedArray try below.

sortedArray =(E[]) Array.newInstance(clazz, size())

Be aware that you need to provide the class of the required object as the clazz

See the answers for this question for more details. How to create a generic array in Java?

chameerar
  • 322
  • 1
  • 2
  • 8