简体   繁体   中英

Class Cast Exception generated while using generics in Java

I am working on a homework assignment and I cannot figure out why I keep getting a class cast exception whenever I try to run my code. I think it is due to the (path.get(i)) but I can not seem to figure out a way to fix it. The error I receive is

 Exception in thread "main" java.lang.ClassCastException: avltreend.BinarySearchTreeND$BSTNodeND cannot be cast to avltreend.AVLtreeND$AVLTreeNode
    at avltreend.AVLtreeND.balancePath(AVLtreeND.java:64)
    at avltreend.AVLtreeND.insert(AVLtreeND.java:27)
    at avltreend.AVLtreeND.TestAVL(AVLtreeND.java:233)
    at avltreend.AVLtreeND.main(AVLtreeND.java:244)
Java Result: 1

Some of the code is below

   private void balancePath(K d) {
    ArrayList<BSTNodeND<K>> path = path(d);
    for (int i = path.size() - 1; i>= 0; i--) {
     //   System.out.println(path);
        AVLTreeNode<K> A = (AVLTreeNode<K>)(path.get(i));
        findheight(A);
        AVLTreeNode<K> POA = (A == root) ? null :
                (AVLTreeNode<K>)(path.get(i - 1));

The error seems to appear when the 5th line above is run.

      class BSTNodeND < L extends Comparable< ? super L > > {
     L data;
     BSTNodeND < L > left, right, parent;

     BSTNodeND (L d)                  {data = d;}
     BSTNodeND (L d, BSTNodeND <L> p) {data = d; parent = p;}

     public String toString () {
        return data.toString();} // end toString method
  } 


   protected class AVLTreeNode<L extends Comparable<? super L>>
      extends BSTNodeND<L> {
    protected int height = 0; // New data field

    public AVLTreeNode(L d) {
      super(d);
    }

And that is the AVLTreeNode class.

I cannot figure out why these two classes are not working together as I have altered a working example and it should work. Thanks for any help you can provide.

If the true runtime type of an object is A, then you cannot cast it to a subclass B. For example,

class A {...}

class B extends A {
    public void announce() { 
        System.out.println("Hi, I'm an instance of B."); 
     }
}

public class Main {
   public static void main(String[] args) {
       A a = new A();
       A b = new B();
       ((B) b).announce(); // Valid
       ((B) a).announce(); // Exception!
   }
}

This is exactly what you are doing, casting an instance of BSTNodeND to its subclass, AVLTreeNode .

Your variable path is an ArrayList of BSTNodeND . When you get an element you are trying to cast it into an AVLTreeNode . That is you are trying to cast the parent class into the child class wich might works if you have only "child" elements in your list but if the type of the object is BSTNodeND then you cannot cast it to its specialized subclass AVLTreeNode .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM