1

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");
    }
}
Amwey
  • 45
  • 4

1 Answers1

1

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

Aarre Laakso
  • 126
  • 4
  • Rather than just providing the solution (and highlighting the changes), it's best if you also explain **what** the issue was and **why** the fix is suggested. – I Stevenson Nov 09 '21 at 23:36
  • Thanks @IStevenson, I have updated my answer to explain what the issue is and why the fix is suggested. – Aarre Laakso Nov 10 '21 at 16:01
  • Here's a pretty good explanation of what changed https://stackoverflow.com/a/51591709/2635670 – BK1NG Oct 21 '22 at 17:20