TheYellowKnight
TheYellowKnight

Reputation: 43

Java DefaultMutableTree incompatible types

Been searching for an answer online but haven't found anything yet. I have created the following method

public void process(DefaultTreeModel tree){
    DefaultMutableTreeNode current = tree.getRoot();
}

However, the compiler is throwing an incompatible type error. The tree is created by creating DefaultMutableTreeNodes from my own class, and then adding them to a DefaultMutableTree (tested and works fine).

Im not sure why the type is incompatible, because when i run the following

public void process(DefaultTreeModel tree){
    Object o = tree.getRoot();
    System.out.println(o.getClass());
}

It outputs:

class javax.swing.tree.DefaultMutableTreeNode

All help much appreciated!

Upvotes: 2

Views: 203

Answers (3)

Fred
Fred

Reputation: 17095

That's because getRoot returns an Object: http://docs.oracle.com/javase/6/docs/api/javax/swing/tree/DefaultTreeModel.html#getRoot()

Try casting:

DefaultMutableTreeNode current = (DefaultMutableTreeNode)tree.getRoot();

Upvotes: 1

arshajii
arshajii

Reputation: 129537

If you take a look at the documentation, you'll see that getRoot returns an Object. You can try casting:

DefaultMutableTreeNode current = (DefaultMutableTreeNode)tree.getRoot();

getClass is probably returning javax.swing.tree.DefaultMutableTreeNode because this object is an instance of a DefaultMutableTreeNode (but its type is still Object, which is why you receive the error).


Relevant documentation:

Upvotes: 1

Bracket
Bracket

Reputation: 432

DefaultTreeModel returns an Object when you call getRoot(). The compiler has no information as to what type it will be at runtime, so it assumes it's an Object and cannot cast it to a DefaultMutableTreeNode.

Even if it's the right class at run time, it cannot know this at compile time. You will have to check it with instanceof

Object o = tree.getRoot();
if(o instanceof DefaultMutableTreeNode) {
    DefaultMutableTreeNode root = (DefaultMutableTreeNode)o;
    ...
}

Upvotes: 1

Related Questions