Cannot cast from Enumeration<TreeNode> to Enumeration<DefaultMutableTreeNode>

Viewed 246

While performing the task, I encountered "Legacy code", it is compiled in Java 8, but not in Java 16, it swears at this particular piece of code.

protected void onCalculate() {
    final ConsoleMapperForTree cm = new ConsoleMapperForTree();
    cm.setVisible(true);
    cm.getConsole().setFont(new Font("Tahoma", 0, 20));
    final DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.tree.getModel().getRoot();
    final Enumeration<DefaultMutableTreeNode> enmFclt = (Enumeration<DefaultMutableTreeNode>)root.children(); // this is highlighted as an error
    while (enmFclt.hasMoreElements()) {
        final DefaultMutableTreeNode fclt = enmFclt.nextElement();
        int nSpec = 0;
        final Enumeration<DefaultMutableTreeNode> enmDep = (Enumeration<DefaultMutableTreeNode>)fclt.children(); // this is highlighted as an error
        while (enmDep.hasMoreElements()) {
            final DefaultMutableTreeNode dep = enmDep.nextElement();
            final Object data = dep.getUserObject();
            if (((Dept)data).spec) {
                ++nSpec;
            }
        }
        System.out.println(fclt + " has " + nSpec + " specdepartments");
    }
}
1 Answers

The issue is that Java wants you to perform the type cast on the elements of the tree rather than on the whole tree. Therefore, try moving the type cast operators as follows:

protected void onCalculate() {
    final ConsoleMapperForTree cm = new ConsoleMapperForTree();
    cm.setVisible(true);
    cm.getConsole().setFont(new Font("Tahoma", 0, 20));
    final DefaultMutableTreeNode root = (DefaultMutableTreeNode)this.tree.getModel().getRoot();
    final Enumeration<TreeNode> enmFclt = root.children(); // this is highlighted as an error
    while (enmFclt.hasMoreElements()) {
        final DefaultMutableTreeNode fclt = (DefaultMutableTreeNode) enmFclt.nextElement();
        int nSpec = 0;
        final Enumeration<TreeNode> enmDep = fclt.children(); // this is highlighted as an error
        while (enmDep.hasMoreElements()) {
            final DefaultMutableTreeNode dep = (DefaultMutableTreeNode) enmDep.nextElement();
            final Object data = dep.getUserObject();
            if (((Dept)data).spec) {
                ++nSpec;
            }
        }
        System.out.println(fclt + " has " + nSpec + " specdepartments");
    }
}

This side-by-side comparison shows the differences (click to make it bigger):

Comparison

Related