所以我有一個類:爲什麼不能投射?
public static class AVLTreeNode <E extends Comparable<E>> extends BST.TreeNode<E> {
protected int height;
public AVLTreeNode(E e) {
super(e);
}
}
擴展另一個類:
public static class TreeNode<E extends Comparable<E>> {
protected E element;
protected TreeNode<E> left;
protected TreeNode<E> right;
public TreeNode(E e) {
element = e;
}
}
而且我創造TreeNode
類型的ArrayList
,並試圖將它轉換爲AVLTreeNode
:
public void balancePath(E e) {
ArrayList<TreeNode<E>> path = path(e);
for (int i = path.size() - 1; i >= 0; i--) {
AVLTreeNode<E> a = (AVLTreeNode<E>)(path.get(i));
//continued code not important...
請注意我的路徑方法返回類型TreeNode<E>
的ArrayList
。但是,當我嘗試將我在列表中的位置i處獲得的節點投射到AVLTreeNode<E>
(TreeNode
的子類型)時,我得到ClassCastException
。
這裏有什麼問題?
編輯以下是完整的堆棧跟蹤
Exception in thread "main" java.lang.ClassCastException: com.jeffsite.chapter27.BinarySearchTree$TreeNode cannot be cast to com.jeffsite.chapter29.AVLTree$AVLTreeNode
at com.jeffsite.chapter29.AVLTree.balancePath(AVLTree.java:102)
at com.jeffsite.chapter29.AVLTree.insert(AVLTree.java:19)
at com.jeffsite.chapter29.TestAVLTree.main(TestAVLTree.java:10)
考慮提供一個[可運行示例](https://開頭計算器.com/help/mcve),它可以證明你的問題。這將導致更少的混淆和更好的響應 – MadProgrammer 2014-12-03 05:27:01
發佈您的整個異常,包括堆棧跟蹤。 – 2014-12-03 05:30:14