Hello I try to write code of AVLTree extend BST Before 4h it works but now no i dont know why. i just add some comment in code.
error :
Exception in thread "main" java.lang.ClassCastException: Arbre$Noeud cannot be cast to ArbreAVL$NoeudAVL
at ArbreAVL.insertion(ArbreAVL.java:162)
at Test.main(Test.java:9)
Code:
public class Arbre {
protected Noeud racine;
protected static class Noeud {
protected int data;
protected Noeud filsG;
protected Noeud filsD;
public Noeud(int data, Noeud filsG, Noeud filsD) {
this.data = data;
this.filsG = filsG;
this.filsD = filsD;
}
public Noeud(int data) {
this.data = data;
this.filsD = null;
this.filsG = null;
}
}
public Arbre() {
this.racine = null;
}
public Arbre(int data) {
this.racine = new Noeud(data);
}
public Arbre(int data, Noeud filsG, Noeud filsD) {
this.racine = new Noeud(data, filsG, filsD);
}
/*
* L’adjonction d’un nouvel élément à un arbre modifie l’arbre.
*/
public void insertion(int data) {
this.racine = insertion(this.racine, data);
}
private Noeud insertion(Noeud racine, int data) {
if (racine == null)
return new Noeud(data);
if (data < racine.data)
racine.filsG = insertion(racine.filsG, data);
else
racine.filsD = insertion(racine.filsD, data);
return racine;
}
/*
* Une méthode booléenne qui teste la présence d’un élément dans l’arbre
*/
public boolean recherche(int data) {
return recherche(this.racine, data);
}
private boolean recherche(Noeud racine, int data) {
if (racine == null)
return false;
else {
if (data < racine.data)
return recherche(racine.filsG, data);
else if (data > racine.data)
return recherche(racine.filsD, data);
else
return true;
}
}
/*
*
*/
public void suppMin() {
if (this.racine != null)
this.racine = suppMin(this.racine);
}
private Noeud suppMin(Noeud n) {
if (n.filsG == null)
return n.filsD;
n.filsG = suppMin(n.filsG);
return n;
}
/*
* recherche le nœud portant la clé à supprimer
*/
public void supprimer(int data) {
this.racine = supprimer(this.racine, data);
}
/*
* recherche le nœud portant la clé à supprimer
*/
private Noeud supprimer(Noeud n, int data) {
if (n == null)
return null;
if (data < n.data)
n.filsG = supprimer(n.filsG, data);
else if (data > n.data)
n.filsD = supprimer(n.filsD, data);
else {
if (n.filsD == null)
return n.filsG;
if (n.filsG == null)
return n.filsD;
Noeud t = n;
n = getMin(t.filsD);
n.filsD = suppMin(t.filsD);
n.filsG = t.filsG;
}
return n;
}
private Noeud getMin(Noeud n) {
if (n == null)
return null;
else if (n.filsG == null)
return n;
else
return getMin(n.filsG);
}
public int hauteur() {
return hauteur(this.racine);
};
public int hauteur(Noeud n) {
if (n == null)
return -1;
else
return 1 + Math.max(hauteur(n.filsG), hauteur(n.filsD));
}
public boolean isVide() {
return (this.racine == null);
}
public Noeud getRacine() {
return racine;
}
public void setRacine(Noeud racine) {
this.racine = racine;
}
/*
* Serialisation
* #see java.lang.Object#toString()
*/
public String toString() {
return toString(this.racine);
}
private String toString(Noeud n) {
if (n == null)
return "()";
else {
String s = "(";
s = s + toString(n.filsG);
s = s + "," + n.data + ",";
s = s + toString(n.filsD);
return s + ")";
}
}
}
public class ArbreAVL extends Arbre{
protected class NoeudAVL extends Noeud {
protected int factorEquilibre;
public NoeudAVL(int cle, Noeud filsG, Noeud filsD, int b) {
super(cle, filsG, filsD);
this.factorEquilibre = b;
}
public NoeudAVL(int cle) {
super(cle);
this.factorEquilibre = 0;
}
/*
* Une rotation rééquilibre une partie de l’arbre en réarrangeant les
* nœuds tout en préservant la propriété qui fait que le nœud gauche est
* plus petit que son père, qui est lui même inférieur à son fils droit;
* cette propriété doit être maintenue pour que l’arbre reste un arbre
* binaire de recherche. Après la rotation, les facteurs d’équilibre de
* tous les nœuds du sous-arbre équilibré sont +1, −1 et 0. Il n’y a que
* quatre types de rotations à réaliser : les GG (gauche-gauche), GD
* (gauche-droite), DD (droite-droite) et DG (droite-gauche).
*/
protected NoeudAVL rotationG() {
NoeudAVL oldRacine = this;
NoeudAVL newRacine = (NoeudAVL) filsD;
oldRacine.filsD = newRacine.filsG;
newRacine.filsG = oldRacine;
int a = oldRacine.factorEquilibre;
int b = newRacine.factorEquilibre;
if (b <= 0) {
newRacine.factorEquilibre = (a >= 1) ? b - 1 : a + b - 2;
oldRacine.factorEquilibre = a - 1;
} else {
newRacine.factorEquilibre = (a <= b) ? a - 2 : b - 1;
oldRacine.factorEquilibre = a - b - 1;
}
return newRacine;
}
protected NoeudAVL rotationD() {
NoeudAVL oldRacine = this;
NoeudAVL newRacine = (NoeudAVL) filsG;
oldRacine.filsG = newRacine.filsD;
newRacine.filsD = oldRacine;
int a = oldRacine.factorEquilibre;
int b = newRacine.factorEquilibre;
if (b <= 0) {
newRacine.factorEquilibre = (b > a) ? b + 1 : a + 2;
oldRacine.factorEquilibre = a - b + 1;
} else {
newRacine.factorEquilibre = (a < 0) ? b + 1 : a + b + 2;
oldRacine.factorEquilibre = a + 1;
}
return newRacine;
}
protected NoeudAVL reequilibreG(int oldfactorEquilibre) {
if ((NoeudAVL) filsG == null) {
factorEquilibre++;
} else if ((((NoeudAVL) filsG).factorEquilibre == 0)
&& (oldfactorEquilibre != 0)) {
factorEquilibre++;
}
return (factorEquilibre > 1) ? equilibrer() : this;
}
protected NoeudAVL reequilibreD(int oldfactorEquilibre) {
if ((NoeudAVL) filsD == null) {
factorEquilibre--;
} else if ((((NoeudAVL) filsD).factorEquilibre == 0)
&& (oldfactorEquilibre != 0)) {
factorEquilibre--;
}
return (factorEquilibre < -1) ? equilibrer() : this;
}
/*
* La méthode principale implante l’algorithme de rééquilibrage
*/
protected NoeudAVL equilibrer() {
if (factorEquilibre < 0) {
if (((NoeudAVL) filsG).factorEquilibre <= 0)
return rotationD();
else {
filsG = ((NoeudAVL) filsG).rotationG();
return rotationD();
}
} else {
if (((NoeudAVL) filsD).factorEquilibre >= 0)
return rotationG();
else {
filsD = ((NoeudAVL) filsD).rotationD();
return rotationG();
}
}
}
public NoeudAVL insertion(int data) {
if (data <= this.data) {
if (filsG != null) {
int oldfactorEquilibre = ((NoeudAVL) filsG).factorEquilibre;
filsG = ((NoeudAVL) filsG).insertion(data);
if ((((NoeudAVL) filsG).factorEquilibre != oldfactorEquilibre)
&& (((NoeudAVL) filsG).factorEquilibre != 0)) {
factorEquilibre--;
}
} else {
filsG = new NoeudAVL(data);
factorEquilibre--;
}
} else {
if (filsD != null) {
int oldfactorEquilibre = ((NoeudAVL) filsD).factorEquilibre;
filsD = ((NoeudAVL) filsD).insertion(data);
if ((((NoeudAVL) filsD).factorEquilibre != oldfactorEquilibre)
&& (((NoeudAVL) filsD).factorEquilibre != 0)) {
factorEquilibre++;
}
} else {
filsD = new NoeudAVL(data);
factorEquilibre++;
}
}
if ((factorEquilibre < -1) || (factorEquilibre > 1))
return equilibrer();
return this;
}
}
public ArbreAVL() {
super();
}
public ArbreAVL(int cle) {
super(cle);
}
public ArbreAVL(int cle, Noeud filsG, Noeud filsD) {
super(cle, filsG, filsD);
}
/*
* EN prenant soin de rééquilibrer l’arbre à chaque étape. On reprend
* simplement les méthodes déjà écrites pour un arbre binaire de recherche
*/
public void insertion(int data) {
if (isVide())
super.insertion(data);
else
racine = ((NoeudAVL) racine).insertion(data);
}
public void supprimer(int data) {
super.supprimer(data);
this.racine = ((NoeudAVL) racine).equilibrer();
}
}
In ArbreAVL constructors, you are using Arbre constructors, by calling super().
They are creating Noeud objects, that you will later cast to NoeudAVL.
In fact, your ArbreAVL class is assuming all elements are NoeudAVL, which is definitely not the case. Either remove this assumption (by using instanceof tests?) or rework your code deeply, by using Generics for example.
Related
I have a method that tests if a binary search tree is an AVL tree, and am not getting the results i want.
here is the code :fg(left child) - fd(right child) - ag(left tree) - Noeud(node) - racine(root)
package cm5_TP_algo;
class Noeud {
int height;
int v;
Noeud fg;
Noeud fd;
Noeud(Noeud fg,int v,Noeud fd){
this.fg=fg;
this.v=v;
this.fd=fd;
}
public String toString(){
String sb = "[";
if (fg!=null)sb += fg.toString();
sb += v;
if (fd!=null)sb += fd.toString();
return sb + "]";
}
boolean testABR(int min, int max) {
if (fg != null && !fg.testABR(min, v)) {
return false;
}
if (fd != null && !fd.testABR(v, max)) {
return false;
}
return v >= min && v <= max;
}
public int calculateHeight() {
int heightLeft = (fg == null) ? 0 : fg.calculateHeight();
int heightRight = (fd == null) ? 0 : fd.calculateHeight();
height = Math.max(heightLeft, heightRight) + 1;
return height;
}
}
public class Arbre {
Noeud racine;
public Arbre(){ racine=null;}
public Arbre(Arbre ag, int v, Arbre ad) {
racine = new Noeud (ag.racine, v, ad.racine);
}
public String toString() {
if (racine == null) { return ""; }
else { return racine.toString(); }
}
public boolean testABR() {
return racine == null || racine.testABR(Integer.MIN_VALUE, Integer.MAX_VALUE);
}
public void inser(int value){
if(racine == null)
racine = new Noeud(null, value, null);
else{
inser(value, racine);
}
}
public void inser(int value, Noeud racine){
if ( racine.v > value && racine.fg == null ) {
racine.fg = new Noeud(null, value, null);
return;
}
else if(racine.v > value && racine.fg != null){
inser(value, racine.fg);
}
if (racine.v < value && racine.fd == null ) {
racine.fd = new Noeud(null, value, null);
return;
}
else if(racine.v < value && racine.fd != null) {
inser(value, racine.fd);
}
}
public boolean membre(int value) {
if(racine == null)
return false;
if(racine.v == value)
return true;
if(racine.v < value && racine.fd != null )
return membre(value, racine.fd);
if(racine.v > value && racine.fg != null)
return membre(value, racine.fg);
return false;
}
private boolean membre(int value, Noeud racine) {
if(racine.v == value)
return true;
if(racine.v < value && racine.fd != null )
return membre(value, racine.fd);
if(racine.v > value && racine.fg != null)
return membre(value, racine.fg);
return false;
}
public void updateHeights() {
if (racine != null) {
racine.calculateHeight();
}
}
private int getHeight(Noeud noeud) {
if (noeud == null) {
return -1;
}
return noeud.height;
}
public boolean testAVL() {
updateHeights();
return checkBalanced();
}
private boolean checkBalanced() {
return checkBalanced(this.racine);
}
private boolean checkBalanced(Noeud node) {
if (node == null) return true;
int balance = getHeight(node.fd) - getHeight(node.fg);
if (Math.abs(balance) > 1) {return false;}
return checkBalanced(node.fd) && checkBalanced(node.fg);
}
public static void main(String[] args) {
Arbre t1= new Arbre( new Arbre() ,1, new Arbre() );
Arbre t2= new Arbre(
new Arbre(
new Arbre( )
, 12,
new Arbre( ))
, 13,
new Arbre() );
Arbre t3= new Arbre( t1,15,t2);
Arbre t4= new Arbre( t2,16,t3);
System.out.println(t1+":"+t1.testAVL());
System.out.println(t2+":"+t2.testAVL());
System.out.println(t3+":"+t3.testAVL());
System.out.println(t4+":"+t4.testAVL());
}
}
The expected result is :
[[12]13]:true
[115[[12]13]]:false
[[[12]13]16[115[[12]13]]]:false
But what i get is :
[[12]13]:false
[115[[12]13]]:false
[[[12]13]16[115[[12]13]]]:false
Is the problem with the testAVL or the updateHeights ?
I'm currently struggling to write a union() method for my AVL (auto balancing) tree IntegerSet Class.
Some requirements for my class:
Integer sets are ordered
Methods must be at most O(NlogN) time
You may not use a built in tree Java library. You must implement your own tree
The union() method: This is the mathematical union on two sets which creates a new set that contains all the elements from both sets. For example, [1, 2, 3] U [2, 3, 5, 6] results in a new set [1, 2, 3, 5, 6].
My thought was to copy the unique elements of each tree into an array, then use my constructor to create a new tree from that array. However, I haven't been able to copy the elements into an array correctly. I'm also wondering if there's a better way to be doing this.
My current code is below:
package dataStructures.AVL;
import java.util.LinkedList;
import java.util.Queue;
public class IntegerSet {
private Node root;
private int size;
public IntegerSet() {
clear();
}
public IntegerSet(int array[]) {
// Add elements of array to Binary Search Tree
for (int i = 0; i < array.length; i++) {
add(array[i]);
}
}
public int magnitude() {
return size;
}
public void clear() {
root = null;
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public boolean add(int newItem) {
boolean added = false;
if (isEmpty()) {
root = new Node(newItem);
size += 1;
added = true;
} else {
added = add(null, root, newItem);
}
return added;
}
private boolean add(Node parent, Node current, int data) {
boolean added = false;
if (current == null) {
int result = data - parent.data; // data.compareTo(parent.data);
if (result < 0) {
parent.leftChild = new Node(data);
} else {
parent.rightChild = new Node(data);
}
size += 1;
return true;
} else if ((data - current.data) < 0) { // (data.compareTo(current.data) < 0) {
added = add(current, current.leftChild, data);
} else if (data - current.data > 0) { // (data.compareTo(current.data) > 0) {
added = add(current, current.rightChild, data);
} else {
return false;
}
fixHeight(current);
if (added) {
rebalance(parent, current);
}
return added;
}
public boolean remove(int itemToRemove) {
if (isEmpty()) {
return false;
} else if (size == 1 && root.data == itemToRemove) { // (size == 1 && root.data.equals(itemToRemove)) {
clear();
return true;
} else if (removeTraversal(null, root, itemToRemove)) {
size -= 1;
return true;
} else {
return false;
}
}
private boolean removeTraversal(Node parent, Node current, int data) {
boolean removed = true;
if (current == null) {
return false;
} else if (data - current.data < 0) { // (data.compareTo(current.data) < 0) {
removed = removeTraversal(current, current.leftChild, data);
} else if (data - current.data > 0) { // (data.compareTo(current.data) > 0) {
removed = removeTraversal(current, current.rightChild, data);
} else {
removeNode(parent, current);
}
fixHeight(current);
if (removed) {
rebalance(parent, current);
}
return removed;
}
private void removeNode(Node parent, Node current) {
if (current.leftChild == null && current.rightChild == null) {
// Remove leaf node
removeCase1(parent, current);
} else if (current.leftChild != null && current.rightChild == null) {
// Remove node with no right child
removeCase2(parent, current);
} else if (current.leftChild == null && current.rightChild != null) {
// Remove node with no left child
removeCase3(parent, current);
} else {
// Remove node with both children
removeCase4(parent, current);
}
fixHeight(parent);
}
private void removeCase1(Node parent, Node current) {
if (parent == null) {
root = null;
} else if (parent.leftChild == current) {
parent.leftChild = null;
} else {
parent.rightChild = null;
}
}
private void removeCase2(Node parent, Node current) {
if (parent == null) {
root = root.leftChild;
} else if (parent.leftChild == current) {
parent.leftChild = current.leftChild;
} else {
parent.rightChild = current.leftChild;
}
current.leftChild = null;
}
private void removeCase3(Node parent, Node current) {
if (parent == null) {
root = root.rightChild;
} else if (parent.leftChild == current) {
parent.leftChild = current.rightChild;
} else {
parent.rightChild = current.rightChild;
}
current.rightChild = null;
}
private void removeCase4(Node parent, Node current) {
Node leftMost = current.rightChild;
Node leftMostParent = current;
while (leftMost.leftChild != null) {
leftMostParent = leftMost;
leftMost = leftMost.leftChild;
}
current.data = leftMost.data;
removeNode(leftMostParent, leftMost);
rebalance(current, current.rightChild);
}
public boolean contains(int itemToFind) {
if (isEmpty()) {
return false;
} else {
Node temp = root;
while (temp != null) {
int result = itemToFind - temp.data;
if (result < 0) {
temp = temp.leftChild;
} else if (result > 0) {
temp = temp.rightChild;
} else {
return true;
}
}
}
return false;
}
public IntegerSet union(IntegerSet other) {
return null;
}
public IntegerSet intersection(IntegerSet other) {
return null;
}
public IntegerSet difference(IntegerSet other) {
return null;
}
public IntegerSet symmetricDifference(IntegerSet other) {
return null;
}
public int getMin() {
if (isEmpty()) {
throw new EmptyCollectionException("Cannot remove from an empty tree.");
} else {
Node temp = root;
while (temp.leftChild != null) {
temp = temp.leftChild;
}
return temp.data;
}
}
public int getMax() {
if (isEmpty()) {
throw new EmptyCollectionException("Cannot remove from an empty tree.");
} else {
Node temp = root;
while (temp.rightChild != null) {
temp = temp.rightChild;
}
return temp.data;
}
}
public int getHeight() {
return getHeight(root);
}
private int getHeight(Node node) {
if (node == null) {
return -1;
}
return Math.max(node.leftHeight, node.rightHeight);
}
private void fixHeight(Node node) {
if (node != null) {
node.leftHeight = getHeight(node.leftChild) + 1;
node.rightHeight = getHeight(node.rightChild) + 1;
}
}
private int balance(Node node) {
// If the balance > 1 imbalance is in left subtree
// If the balance < -1 imbalance is in right subtree
return node.leftHeight - node.rightHeight;
}
private Node rightRotation(Node n) {
Node c = n.leftChild;
Node t2 = c.rightChild;
c.rightChild = n;
n.leftChild = t2;
fixHeight(n);
fixHeight(c);
return c;
}
private Node leftRotation(Node n) {
Node c = n.rightChild;
Node t2 = c.leftChild;
c.leftChild = n;
n.rightChild = t2;
fixHeight(n);
fixHeight(c);
return c;
}
private void rebalance(Node parent, Node node) {
if (node == null) {
return;
}
// Imbalance in left subtree
if (balance(node) > 1) {
// Handles case III
if (balance(node.leftChild) < 0) {
// leftRotation
node.leftChild = leftRotation(node.leftChild);
}
if (parent == null) {
root = rightRotation(node);
} else if (parent.leftChild == node) {
parent.leftChild = rightRotation(node);
} else {
parent.rightChild = rightRotation(node);
}
// Imbalance in right subtree
} else if (balance(node) < -1) {
// Handle case IV
if (balance(node.rightChild) > 0) {
node.rightChild = rightRotation(node.rightChild);
}
if (parent == null) {
root = leftRotation(node);
} else if (parent.leftChild == node) {
parent.leftChild = leftRotation(node);
} else {
parent.rightChild = leftRotation(node);
}
}
}
#Override
public String toString() {
return levelOrderString();
}
public String levelOrderString() {
StringBuffer sb = new StringBuffer();
sb.append("{");
if (!isEmpty()) {
Queue<Node> q = new LinkedList<>();
q.add(root);
Node current = null;
while (!q.isEmpty()) {
current = q.remove();
if (current.leftChild != null) {
q.add(current.leftChild);
}
if (current.rightChild != null) {
q.add(current.rightChild);
}
sb.append(current);
if (!q.isEmpty()) {
sb.append(", ");
}
}
}
sb.append("}");
return sb.toString();
}
public String inOrderToString() {
StringBuffer sb = new StringBuffer();
sb.append("{ ");
inOrderToString(root, sb);
sb.append(" }");
return sb.toString();
}
private void inOrderToString(Node current, StringBuffer sb) {
if (current != null) {
inOrderToString(current.leftChild, sb);
if (current.leftChild != null) {
sb.append(", ");
}
sb.append(current.data);
if (current.rightChild != null) {
sb.append(", ");
}
inOrderToString(current.rightChild, sb);
}
}
// You may add any methods or constructors
// to this class that you see fit.
private class Node {
private int data;
private Node leftChild;
private Node rightChild;
private int leftHeight;
private int rightHeight;
public Node(int data) {
this.data = data;
}
public String toString() {
String formatter = "(%s | %s | %s)";
String leftString = leftChild != null ? Integer.toString(leftChild.data) : "";
String rightString = rightChild != null ? Integer.toString(rightChild.data) : "";
return String.format(formatter, Integer.toString(data), leftString, rightString);
}
}
}
I am learning about Binary Search Tree and working on a project. When I tried to delete the first node I inserted, it doesn't delete and still show that node when I call showAll method. Is that how Binary Search Tree works or did I do something incorrectly?
Thanks,
Here is the code for BinarySearchTree class:
public class BinarySearchTree_Pham {
TreeNode root;
public BinarySearchTree_Pham() {
root = null;
}
public boolean insert(Student_Pham newStudent) {
TreeNodeWrapper p = new TreeNodeWrapper();
TreeNodeWrapper c = new TreeNodeWrapper();
TreeNode n = new TreeNode();
if(n == null)
return false;
else {
n.node = newStudent.deepCopy();
n.lc = null;
n.rc = null;
if(root == null) {
root = n;
}
else {
findNode(newStudent.getId(), p, c);
if(newStudent.getId().compareTo(p.get().node.getId()) < 0)
p.get().lc = n;
else
p.get().rc = n;
}
return true;
}
} //end insert
public Student_Pham fetch(String id) {
boolean found;
TreeNodeWrapper p = new TreeNodeWrapper();
TreeNodeWrapper c = new TreeNodeWrapper();
found = findNode(id, p, c);
if (found == true)
return c.get().node.deepCopy();
else
return null;
} //end fetch
public boolean delete(String id) {
boolean found;
TreeNodeWrapper p = new TreeNodeWrapper();
TreeNodeWrapper c = new TreeNodeWrapper();
TreeNode largest;
TreeNode nextLargest;
found = findNode(id, p, c);
if(found == false)
return false;
else {
if(c.get().lc == null && c.get().rc == null) {
if (p.get().lc == c.get())
p.get().lc = null;
else
p.get().rc = null;
} //end case 1
else if (c.get().lc == null || c.get().rc == null) {
if (p.get().lc == c.get()) {
if (c.get().lc != null)
p.get().lc = c.get().lc;
else
p.get().lc = c.get().rc;
}
else {
if (c.get().lc != null)
p.get().rc = c.get().lc;
else
p.get().rc = c.get().rc;
}
} // end case 2
else {
nextLargest = c.get().lc;
largest = nextLargest.rc;
if (largest != null) {
while (largest.rc != null) {
nextLargest = largest;
largest = largest.rc;
}
c.get().node = largest.node;
nextLargest.rc = largest.lc;
}
else {
nextLargest.rc = c.get().rc;
if (p.get().lc == c.get())
p.get().lc =nextLargest;
else
p.get().rc = nextLargest;
}
} // end case 3
return true;
}
} // end of delete
public boolean update(String id, Student_Pham newStudent) {
if(delete(id) == false)
return false;
else if (insert(newStudent) == false)
return false;
return true;
} // end update
public void showAll() {
if (root == null)
System.out.println("Structure is empty.");
else
LNRoutputTraversal(root);
} //end showAll
private void LNRoutputTraversal(TreeNode root) {
if (root.lc != null)
LNRoutputTraversal(root.lc);
System.out.println(root.node);
if (root.rc != null)
LNRoutputTraversal(root.rc);
}
public class TreeNode {
private Student_Pham node;
private TreeNode lc;
private TreeNode rc;
public TreeNode() {}
}
private boolean findNode(String targetKey, TreeNodeWrapper parent, TreeNodeWrapper child) {
parent.set(root);
child.set(root);
if (root == null)
return true;
while (child.get() != null) {
if(child.get().node.getId().compareTo(targetKey) == 0)
return true;
else {
parent.set(child.get());
if(targetKey.compareTo(child.get().node.getId()) < 0)
child.set(child.get().lc);
else
child.set(child.get().rc);
}
} //end while
return false;
}
public class TreeNodeWrapper {
TreeNode treeRef = null;
public TreeNodeWrapper() {}
public TreeNode get() {return treeRef;}
public void set(TreeNode t) {treeRef = t;}
}
}
} else if (xpp.getName().equalsIgnoreCase("pressure")) {
if (insideItem) {
Pressure.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("weatherIconUrl")) {
if (insideItem) {
iconImg.add(xpp.nextText());
}
I am trying to call weather items from weather api. All text items that I am trying to call are ok but iconImg is not. iconImg.add(xpp.nextText()) gives an error. I probably shouldn't use imageview here, but I don't know what else to do. Any help will be appreciated.
Here is the entire code:
public class HavaDurumu2 extends FragmentActivity {
private String urll;
public TextView xmlShow;
private EditText lattitudeEditText;
private EditText longitudeEditText;
private Button devam;
public Intent dataShowIntent;
public TextView succcess;
public TextView appTitle;
public TextView lat;
public TextView lon;
GoogleMap googlelMap;
Marker mk;
Button fav;
TextView error;
Intent vj;
public static List<String> Time;
public static List<String> CTemperature;
public static List<String> Wind_Speed_Kmph;
public static List<String> Water_Temperature_C;
public static List<String> Humidity;
public static List<String> Significant_Wave_Height;
public static List<String> Swell_Height;
public static List<String> Swell_Direction;
public static List<String> Swell_Period;
public static List<String> Pressure;
public static List<String> Visibility;
public static List<String> Weather_Condition;
public static List<String> Warning_level;
public static List<Double> Wind_Speed_Kmph_Num;
public static List<Double> Wind_Speed_mps_Num;
public static List<String> Wind_Dir_Degree;
public static List<Double> Beaufort;
public static List<String> nearest_longitude;
public static List<String> nearest_latitude;
public static List<String> nearest_distance_mile;
public static List<String> date;
public static List<String> maxtempc;
public static List<String> mintempc;
public static List<String> nearest_location_name;
public static List<String> sunrise;
public static List<String> sunset;
public static List<ImageView> iconImg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_havadurumu2);
if (GooglePlayServicesUtil.isGooglePlayServicesAvailable(this) == ConnectionResult.SUCCESS) {
SupportMapFragment mapfragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
googlelMap = mapfragment.getMap();
lattitudeEditText = (EditText) findViewById(R.id.enEditText);
longitudeEditText = (EditText) findViewById(R.id.boyEditText);
lat = (TextView) findViewById(R.id.enlem);
lon = (TextView) findViewById(R.id.boylam);
devam = (Button) findViewById(R.id.devam);
googlelMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(39, 30), 5.0f));
lattitudeEditText.clearFocus();
longitudeEditText.clearFocus();
Time = new ArrayList<String>();
CTemperature = new ArrayList<String>();
Wind_Speed_Kmph = new ArrayList<String>();
Water_Temperature_C = new ArrayList<String>();
Humidity = new ArrayList<String>();
Significant_Wave_Height = new ArrayList<String>();
Swell_Height = new ArrayList<String>();
Swell_Direction = new ArrayList<String>();
Swell_Period = new ArrayList<String>();
Pressure = new ArrayList<String>();
Visibility = new ArrayList<String>();
Warning_level = new ArrayList<String>();
Wind_Dir_Degree = new ArrayList<String>();
sunrise = new ArrayList<String>();
sunset = new ArrayList<String>();
Wind_Speed_Kmph_Num = new ArrayList<Double>();
Wind_Speed_mps_Num = new ArrayList<Double>();
Beaufort = new ArrayList<Double>();
Weather_Condition = new ArrayList<String>();
iconImg =new ArrayList<ImageView>();
nearest_longitude = new ArrayList<String>();
nearest_latitude = new ArrayList<String>();
nearest_distance_mile = new ArrayList<String>();
date = new ArrayList<String>();
maxtempc = new ArrayList<String>();
mintempc = new ArrayList<String>();
nearest_location_name = new ArrayList<String>();
String message = "Yer secmek için ekrana uzun basın";
Toast t = Toast.makeText(this, message, Toast.LENGTH_LONG);
t.show();
googlelMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng point) {
if (mk == null) {
mk = googlelMap.addMarker(new MarkerOptions().position(point).snippet("Enlem : " + point.latitude + "Boylam : " + point.longitude).title("Kordinatlar"));
lattitudeEditText.setText(("" + point.latitude).substring(0, 9));
longitudeEditText.setText(("" + point.longitude).substring(0, 9));
// fav.setVisibility(View.VISIBLE);
} else {
mk.remove();
mk = googlelMap.addMarker(new MarkerOptions().position(point).snippet("Enlem : " + point.latitude + "Boylam : " + point.longitude).title("Kordinatlar"));
lattitudeEditText.setText("" + point.latitude);
longitudeEditText.setText("" + point.longitude);
}
}
});
} else {
String message = "Google Play servisi uygun değil";
Toast.makeText(HavaDurumu2.this, message, Toast.LENGTH_LONG).show();
//GooglePlayServicesUtil.getErrorDialog(GooglePlayServicesUtil.isGooglePlayServicesAvailable(this),this,1001).show();
}
}
public void clickHandler(View v) {
if (lattitudeEditText.getText().toString().isEmpty() && longitudeEditText.getText().toString().isEmpty()) {
String message = "Lütfen Bir Yer Seçin";
Toast.makeText(HavaDurumu2.this, "Lütfen Bir Yer Seçin", Toast.LENGTH_SHORT).show();
} else if (networkStatus(HavaDurumu2.this)) {
urll = "http://api.worldweatheronline.com/free/v2/marine.ashx?q=" + lattitudeEditText.getText().toString() + "%2C" + longitudeEditText.getText().toString() + "&tp=3&lang=tr&format=xml&key=......";
new LoadAssync().execute();
} else {
String message = "İnternet Bağlantısı Bulunamdı";
Toast toast = Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT);
toast.setGravity(0, 0, 300);
toast.show();
}
}
private class LoadAssync extends AsyncTask<String, Void, Void> {
ProgressDialog dialog = new ProgressDialog(HavaDurumu2.this);
protected void onPreExecute() {
dialog.setMessage("Bilgiler Alınıyor...");
dialog.show();
}
protected Void doInBackground(final String... args) {
try {
getdata();
updateDateandTemperature();
updatedirection();
updateAstronomy();
updateweather();
Log.i("", String.valueOf(date.size()) + " " + String.valueOf(Wind_Dir_Degree.size()) + " " + String.valueOf(sunrise.size()));
} catch (Exception ex) {
String message = "Hata oluştu";
Toast.makeText(HavaDurumu2.this, message, Toast.LENGTH_SHORT).show();
}
return null;
}
protected void onPostExecute(final Void unused) {
if (dialog.isShowing()) {
dialog.dismiss();
if (Time.size() == 0) {
nearest_distance_mile.clear();
nearest_latitude.clear();
nearest_location_name.clear();
nearest_longitude.clear();
maxtempc.clear();
mintempc.clear();
date.clear();
sunrise.clear();
sunset.clear();
String message = "Bu bölge için durum bilgisi yok";
Toast.makeText(HavaDurumu2.this, message, Toast.LENGTH_SHORT).show();
} else {
Intent m = new Intent(HavaDurumu2.this, ShowWeather.class);
startActivity(m);
}
}
}
}
private void updatefeeds() {
try {
Time.clear();
CTemperature.clear();
Wind_Speed_Kmph.clear();
Wind_Speed_Kmph_Num = new ArrayList<Double>();
Water_Temperature_C.clear();
Humidity.clear();
;
Significant_Wave_Height.clear();
Swell_Height.clear();
Swell_Direction.clear();
Swell_Period.clear();
Pressure.clear();
Visibility.clear();
Warning_level.clear();
Beaufort.clear();
Wind_Dir_Degree.clear();
Weather_Condition.clear();
iconImg.clear();
URL url = new URL(urll);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("hourly")) {
insideItem = true;
}
else if (xpp.getName().equalsIgnoreCase("time")) {
if (insideItem) {
Time.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("tempc")) {
if (insideItem) {
CTemperature.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("windspeedKmph")) {
if (insideItem) {
Wind_Speed_Kmph.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("winddirdegree")) {
if (insideItem) {
Wind_Dir_Degree.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("waterTemp_C")) {
if (insideItem) {
Water_Temperature_C.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("humidity")) {
if (insideItem) {
Humidity.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("sigHeight_m")) {
if (insideItem) {
Significant_Wave_Height.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("swellHeight_m")) {
if (insideItem) {
Swell_Height.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("swellDir")) {
if (insideItem) {
Swell_Direction.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("swellPeriod_secs")) {
if (insideItem) {
Swell_Period.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("visibility")) {
if (insideItem) {
Visibility.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("pressure")) {
if (insideItem) {
Pressure.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("weatherIconUrl")) {
if (insideItem) {
iconImg.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("lang_tr")) {
if (insideItem) {
Weather_Condition.add(xpp.nextText());
Log.i("", Weather_Condition.get(Weather_Condition.size() - 1));
}
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("hourly")) {
insideItem = false;
}
eventType = xpp.next();
}
} catch (Exception e) {
Log.i("", e.toString());
}
}
public InputStream getInputStream(URL url) {
try {
return url.openConnection().getInputStream();
} catch (IOException e) {
return null;
}
}
public void updateDateandTemperature() {
try {
URL url = new URL(urll);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
date.clear();
maxtempc.clear();
mintempc.clear();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("weather")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("date")) {
if (insideItem) {
date.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("maxtempc")) {
if (insideItem) {
maxtempc.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("mintempc")) {
if (insideItem) {
mintempc.add(xpp.nextText());
}
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("weather")) {
insideItem = false;
}
eventType = xpp.next();
}
} catch (Exception e) {
}
}
public void updateAstronomy() {
try {
URL url = new URL(urll);
XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
factory.setNamespaceAware(false);
XmlPullParser xpp = factory.newPullParser();
sunrise.clear();
sunset.clear();
xpp.setInput(getInputStream(url), "UTF_8");
boolean insideItem = false;
int eventType = xpp.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if (xpp.getName().equalsIgnoreCase("astronomy")) {
insideItem = true;
} else if (xpp.getName().equalsIgnoreCase("sunrise")) {
if (insideItem) {
sunrise.add(xpp.nextText());
}
} else if (xpp.getName().equalsIgnoreCase("sunset")) {
if (insideItem) {
sunset.add(xpp.nextText());
}
}
} else if (eventType == XmlPullParser.END_TAG && xpp.getName().equalsIgnoreCase("weather")) {
insideItem = false;
}
eventType = xpp.next();
}
} catch (Exception e) {
}
}
public void getdata() {
updatefeeds();
for (int i = 0; i <= Wind_Speed_Kmph.size() - 1; i++)
Wind_Speed_Kmph_Num.add(Double.parseDouble(Wind_Speed_Kmph.get(i)));
for (int i = 0; i <= Wind_Speed_Kmph.size() - 1; i++)
Wind_Speed_mps_Num.add(Wind_Speed_Kmph_Num.get(i) * 1000.0 / 3600.0);
for (int i = 0; i <= Wind_Speed_mps_Num.size() - 1; i++)
Beaufort.add(Math.cbrt((Wind_Speed_mps_Num.get(i) / 0.837) * (Wind_Speed_mps_Num.get(i) / 0.837)));
updatewarninglevels();
}
public void updatedirection() {
for (int i = 0; i < Swell_Direction.size(); i++) {
if (Double.parseDouble(Swell_Direction.get(i)) >= 337.5 || Double.parseDouble(Swell_Direction.get(i)) <= 22.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°K");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 67.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°KD");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 112.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°D");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 157.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°GD");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 202.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°G");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 247.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°GB");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 292.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°B");
else if (Double.parseDouble(Swell_Direction.get(i)) <= 337.5)
Swell_Direction.set(i, Swell_Direction.get(i) + "°KB");
}
for (int i = 0; i < Wind_Dir_Degree.size(); i++) {
if (Double.parseDouble(Wind_Dir_Degree.get(i)) >= 337.5 || Double.parseDouble(Wind_Dir_Degree.get(i)) <= 22.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°K");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 67.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°KD");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 112.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°D");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 157.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°GD");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 202.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°G");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 247.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°GB");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 292.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°B");
else if (Double.parseDouble(Wind_Dir_Degree.get(i)) <= 337.5)
Wind_Dir_Degree.set(i, Wind_Dir_Degree.get(i) + "°KB");
}
}
public void updatewarninglevels() {
for (int i = 0; i <= Beaufort.size() - 1; i++) {
if (Beaufort.get(i) > 0 && Beaufort.get(i) <= 3.5)
Warning_level.add("Sakin 0 - 3.5 Bofor Skalası");
else if (Beaufort.get(i) <= 5.6)
Warning_level.add("Rüzgarlı 3.5- 5.5 Bofor Skalası");
else if (Beaufort.get(i) <= 9.5)
Warning_level.add("Fırtına 5.6- 9.5 Bofor Skalası");
else
Warning_level.add("Kasırga 9.5 - üstü Bofor Skalası");
}
}
public void updateweather() {
for (int i = 0; i <= Weather_Condition.size() - 1; i++) {
}
}
any idea?
Use String instead.
String artistPic = null; instead of imageview
get the value like
artistPic = readArtistPic(parser);
first time asking around here. I'm doing an AVLTree generic and there is a method in the Node that gives me an Iterator that returns me a Object array. The thing is that when I try to get that array with the objects of one of my none generic classes it sends me this.
Exception in thread "main" java.lang.ClassCastException: [LestructuraDeDatos.NodoAVL; cannt be cast to [Lmundo.Categoria;
Here is the node class
public class NodoAVL <T extends Comparable <T>>
{
//--------------------------------------------------------------------------------------------
//Atributos
//--------------------------------------------------------------------------------------------
private NodoAVL<T> izquierdo;
private NodoAVL<T> derecho;
private T elemento;
private String criterio;
//--------------------------------------------------------------------------------------------
//Constructor
//--------------------------------------------------------------------------------------------
public NodoAVL(T elem, String crit)
{
elemento = elem;
izquierdo = null;
derecho = null;
criterio = crit;
}
//--------------------------------------------------------------------------------------------
//Metodos
//--------------------------------------------------------------------------------------------
public NodoAVL<T> getIzquierdo() {
return izquierdo;
}
public void setIzquierdo(NodoAVL<T> izquierdo) {
this.izquierdo = izquierdo;
}
public NodoAVL<T> getDerecho() {
return derecho;
}
public void setDerecho(NodoAVL<T> derecho) {
this.derecho = derecho;
}
public String getCriterio() {
return criterio;
}
public void setCriterio(String criterio) {
this.criterio = criterio;
}
public boolean soyHoja()
{
if(izquierdo == null && derecho == null)
{
return true;
}
return false;
}
public T getElemento() {
return elemento;
}
public void setElemento(T elemento) {
this.elemento = elemento;
}
public void agregarElemento(T elemento, String Crit)
{
//Buscarlo antes de agregar, no puede haber iguales en el arbol
if(buscarElemento(Crit)==null)
if(soyHoja())
{
if(elemento.compareTo(this.elemento)>0)
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento, Crit);
setDerecho(nuevo);
}else if(elemento.compareTo(this.elemento)<0)
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento, Crit);
setIzquierdo(nuevo);
}
}else
{
NodoAVL<T> nuevo = new NodoAVL<T>(elemento,Crit);
if(this.elemento.compareTo(elemento)>0 && izquierdo == null)
{
izquierdo = nuevo;
}
else if(this.elemento.compareTo(elemento)>0)
{
izquierdo.agregarElemento(elemento,Crit);
}
else if(this.elemento.compareTo(elemento)<0 && derecho == null)
{
derecho = nuevo;
}
else if( this.elemento.compareTo(elemento)<0)
{
derecho.agregarElemento(elemento, Crit);
}
}
balanciarSubArbol();
}
public NodoAVL<T> rotarIzq(NodoAVL<T> rotar)
{
NodoAVL<T> temp = rotar.derecho;
rotar.setDerecho(temp.izquierdo);
temp.setIzquierdo(rotar);
return temp;
}
public NodoAVL<T> rotarDer(NodoAVL<T> rotar)
{
NodoAVL<T> temp = rotar.izquierdo;
rotar.setIzquierdo(temp.derecho);
temp.setDerecho(rotar);
return temp;
}
public int darBalance()
{
if(soyHoja())
{
return 0;
}
else
{
int izq = (izquierdo == null)?0:izquierdo.darAltura();
int der = (derecho == null)? 0 :derecho.darAltura();
return (izq - der);
}
}
public NodoAVL<T> dobleRotacionDerIzq(NodoAVL<T> nodo)
{
nodo.setDerecho(rotarDer(nodo.getDerecho()));
return rotarIzq(nodo);
}
public NodoAVL<T> dobleRotacionIzqDer(NodoAVL<T> nodo)
{
nodo.setIzquierdo(rotarIzq(nodo.getIzquierdo()));
return rotarDer(nodo);
}
public void balanciarSubArbol()
{
int valor = darBalance();
if(-2==valor || valor==2)
{
if(valor<0 && derecho.darBalance()<0)
{
if(derecho.darBalance()<-2)
{
derecho.balanciarSubArbol();
}else
{
rotarIzq(this);
}
}else if(valor<0 && derecho.darBalance()>0)
{
if(derecho.darBalance()>2)
{
derecho.balanciarSubArbol();
}else
{
dobleRotacionDerIzq(this);
}
}else if(valor>0 && izquierdo.darBalance()>0)
{
if(izquierdo.darBalance()>2)
{
izquierdo.balanciarSubArbol();
}else
{
rotarDer(this);
}
}else if(valor>0 && izquierdo.darBalance()<0)
{
if(izquierdo.darBalance()<-2)
{
izquierdo.balanciarSubArbol();
}else
{
dobleRotacionIzqDer(this);
}
}
}
}
public NodoAVL<T> eliminarElemento(T elemento)
{
if(soyHoja() && this.elemento==elemento)
{
return null;
}else if(soyHoja() && this.elemento!=elemento)
{
return this;
}
else
{
if(this.elemento.compareTo(elemento)==0)
{
if(izquierdo != null && derecho != null)
{
NodoAVL<T> temp = derecho;
izquierdo.setDerecho(temp.getIzquierdo());
temp.setIzquierdo(izquierdo);
return temp;
}
else if(izquierdo != null)
{
return izquierdo;
}
else
{
return derecho;
}
}
else if(this.elemento.compareTo(elemento)>0)
{
izquierdo = izquierdo.eliminarElemento(elemento);
return this;
}
else if(this.elemento.compareTo(elemento)<0)
{
derecho = derecho.eliminarElemento(elemento);
return this;
}
balanciarSubArbol();
return this;
}
}
public T buscarElemento(String criterio)
{
if(this.criterio.equalsIgnoreCase(criterio))
{
return this.elemento;
}
else
{
T izq = (izquierdo != null)?izquierdo.buscarElemento(criterio):null;
T der = (derecho != null) ? derecho.buscarElemento(criterio):null;
if(izq != null)
{
return izq;
}else if(der != null)
{
return der;
}
}
return null;
}
public IteradorAVL<T> darElementos()
{
IteradorAVL<T> ite = new IteradorAVL<T> (this);
return ite;
}
public int darPeso()
{
if(soyHoja())
{
return 1;
}else
{
int izq = (izquierdo == null)? 0: izquierdo.darPeso();
int der = (derecho == null) ? 0:derecho.darPeso();
return (izq+der+1);
}
}
public int darAltura()
{
if(soyHoja())
{
return 1;
}
else
{
int izq = ( izquierdo == null ) ? 0 : izquierdo.darAltura( );
int der = ( derecho == null ) ? 0 : derecho.darAltura( );
return(izq>der || izq == der)?izq+1:der+1;
}
}
}
and the iterator class
public class IteradorAVL<T extends Comparable <T>> implements Iterator<T>{
//--------------------------------------------------------------------------------------------
//Atributos
//--------------------------------------------------------------------------------------------
private NodoAVL<T> arbolitoAVL;
private Object [] elementos;
private int posActual;
private int total;
private Stack<NodoAVL> nodePath = new Stack<NodoAVL>();
//--------------------------------------------------------------------------------------------
//Constructor
//--------------------------------------------------------------------------------------------
public IteradorAVL ( NodoAVL <T> nodo)
{
arbolitoAVL = nodo;
posActual = 0;
total = nodo.darPeso();
elementos = new NodoAVL[total];
}
//--------------------------------------------------------------------------------------------
//Metodos
//--------------------------------------------------------------------------------------------
#Override
public boolean hasNext()
{
return(total>posActual)?true:false;
}
#Override
public T next() {
T siguienteT =null;
NodoAVL<T> respuesta = arbolitoAVL;
//Guardo el nodo actual en la lista
//Avancce
while (arbolitoAVL != null) {
nodePath.push(arbolitoAVL);
elementos[posActual] = arbolitoAVL;
arbolitoAVL = arbolitoAVL.getIzquierdo();
posActual++;
}
if (!nodePath.isEmpty()) {
arbolitoAVL = nodePath.pop();
posActual++;
elementos[posActual] = arbolitoAVL;
siguienteT = arbolitoAVL.getElemento();
arbolitoAVL = arbolitoAVL.getDerecho();
}
return siguienteT;
}
#Override
public void remove() {
// TODO Auto-generated method stub
}
public Object[] darArreglo()
{
return elementos;
}
The reason ClassCastException occurs is only one that your trying to typecast an object of one class to an object of another class which are not compatible.
Example :
Object i = Integer.valueOf(42);
String s = (String)i; // ClassCastException thrown here.