Chazilian
Chazilian

Reputation: 73

Casting error in BST iterator

I'm having trouble with casting for generics. What I'm trying to do is use a generic iterator to help me print out what is in my Binary Search Tree. However the for loop I'm implementing says their are incompatible types and therefore will not run. Wanted to get some insight on to what I'm doing wrong here.

public class BinarySearchTree<AnyType extends Comparable<? super AnyType>> implements Iterable{...}

public class MainBST { 

    public <AnyType> void print(BinarySearchTree<? extends AnyType> t ) { 

        for(AnyType x : t) //incompatible type
            System.out.print(x + ", "); 

             System.out.println("\n");
        }
    }

Upvotes: 2

Views: 75

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500485

The problem is your BinarySearchTree declaration. It's implementing the raw Iterable type, when it should be implementing Iterable<AnyType>. With the raw Iterator type, the code using the enhanced-for loop only knows that the values will be compatible with Object - so you could change your loop to for (Object x : t) but of course that's not what you really want.

I've reproduced the compile-time error you've shown, and then fixed it by changing the declaration to:

class BinarySearchTree<AnyType extends Comparable<? super AnyType>> 
    implements Iterable<AnyType> {
    ...
}

(And then changing the iterator method to return Iterator<AnyType> of course.)

Upvotes: 3

Related Questions