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.
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 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;}
}
}
I have a custom hashtable implementation in java.
public class HashSet<T> implements HashTableInterface<T> {
private static int DEFAULT_ARRAY_SIZE = 10;
private T[] items;
public HashSet() {
final T[] items = (T[]) new Object[DEFAULT_ARRAY_SIZE];
this.items = items;
}
#Override
public boolean add(T item) {
int index = getIndex(item);
do {
if (items[index] != null) {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
} else {
items[index] = item;
break;
}
} while (index != getIndex(item));
return true;
}
#Override
public boolean remove(T item) {
if (contains(item)) {
items[getIndex(item)] = null;
return true;
} else {
return false;
}
}
#Override
public boolean contains(T item) {
T itemArray = items[getIndex(item)];
if (item.equals(itemArray)) {
return true;
} else {
int index = (getIndex(item) + 1) % DEFAULT_ARRAY_SIZE;
do {
if (items[index] != null) {
if (items[index].equals(item)) {
return true;
} else {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
}
} else {
break;
}
} while (index != getIndex(item));
}
return items[getIndex(item)] != null;
}
#Override
public int getIndex(T item) {
return item.hashCode() % DEFAULT_ARRAY_SIZE;
}
#Override
public int size() {
int count = 0;
for (T item : items) {
if (item != null) {
count++;
}
}
return count;
}
#Override
public String toString() {
return items.toString();
}}
In my add method I want to check if the place where the item would be stored is free, if not it should go to the next index. Until it finds an empty place.
My code works but I think, there could be a better way to do this.
public boolean add(T item) {
int index = getIndex(item);
do {
if (items[index] != null) {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
} else {
items[index] = item;
break;
}
} while (index != getIndex(item));
return true;
}
I have the same problem in the contains method
public boolean contains(T item) {
T itemArray = items[getIndex(item)];
if (item.equals(itemArray)) {
return true;
} else {
int index = (getIndex(item) + 1) % DEFAULT_ARRAY_SIZE;
do {
if (items[index] != null) {
if (items[index].equals(item)) {
return true;
} else {
index = (index + 1) % DEFAULT_ARRAY_SIZE;
}
} else {
break;
}
} while (index != getIndex(item));
}
return items[getIndex(item)] != null;
}
There a many different ways to do collision avoidance, what you did is called "Linear Probing".
There is also (reference here)
Quadratic probing
Double hashing
And schemes that use linked lists for colliding values.
All of these have different tradeoffs which you should inform yourself on to make an informed decision.
im trying to make a linked list of generic objects. i have the linked list made now i have to load a file of movies(in movie class i have genre,rating, title).first i need to load a CVS file of movies the create Hash Table Object which contains an array of Linked List objects which in turn stores the Movies. so for example in a movie class i will have genre and genre can be many. i want to get hash code of genre and then store that in a hash table of arrayed linked list. that's what im using the LoadingMovie class for.
i dont know what im doing as it my first time working with hash tables and link list etc.this is what i have so far:
public class List<T> {
private Node<T> head;
private Node<T> tail;
private int count;
public void append(T d) {
if (head == null) {
head = tail = new Node<T>(d);
} else {
tail.insertAfter(d);
tail = tail.getNext();
count++;
}
}
public void prepend(T d) {
if (head == null) {
head = tail = new Node<T>(d);
} else {
head.insertBefore(d);
head = head.getPrevious();
count++;
}
}
public void removeHead() {
if (head == null) {
return;
} else if (head == tail) {
head = tail = null;
count--;
return;
}
head = head.getNext();
count--;
}
public ListIterator<T> getIterator() {
return new ListIterator<T>(this, head);
}
public void add(ListIterator<T> iter, T data) {
if (iter.getList() != this) {
return;
}
if (!iter.isValid()) {
append(data);
} else {
iter.getCurrentNode().insertAfter(data);
count++;
if (iter.getCurrentNode() == tail) {
tail = iter.getCurrentNode().getNext();
}
}
}
public void remove(ListIterator<T> iter) {
if (iter.getList() != this) {
return;
}
Node<T> node = iter.getCurrentNode();
if (node == null) {
return;
} else if (node == head) {
removeHead();
} else if (node == tail) {
removeTail();
} else {
Node<T> ptn = node.getPrevious();
ptn.setNext(node.getNext());
node.getNext().setPrevious(ptn);
iter.advance();
count--;
}
}
public void removeTail() {
if (head == null) {
} else if (head == tail) {
head = tail = null;
count--;
} else {
Node<T> node = head;
while (node.getNext() != tail) {
node = node.getNext();
}
tail = node;
tail.setNext(null);
count--;
}
}
public void display() {
ListIterator<T> iter = getIterator();
do {
System.out.println(iter.item()+ " , ");
iter.advance();
} while (iter.isValid());
}
public void displayReverse() {
ListIterator<T> iter = getIterator();
iter.end();
do {
System.out.print(iter.item() + " , ");
iter.previous();
} while (iter.isValid());
}
public Node<T> getHead() {
return head;
}
public Node<T> getTail() {
return tail;
}
public int getCount() {
return count;
}
public void setHead(Node<T> head) {
this.head = head;
}
public void setTail(Node<T> tail) {
this.tail = tail;
}
public void setCount(int count) {
this.count = count;
}
#Override
public int hashCode() {
int hash = 5;
hash = 89 * hash + Objects.hashCode(this.head);
hash = 89 * hash + Objects.hashCode(this.tail);
hash = 89 * hash + this.count;
return hash;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final List<?> other = (List<?>) obj;
if (!Objects.equals(this.head, other.head)) {
return false;
}
if (!Objects.equals(this.tail, other.tail)) {
return false;
}
if (this.count != other.count) {
return false;
}
return true;
}
this is the node class :
public class Node<T> {
T anElement;
Node<T> next;
Node<T> previous;
public Node() {
anElement = null;
next = null;
}
public Node(T elem) {
anElement = elem;
next = null;
}
public T getAnElement() {
return anElement;
}
public void setAnElement(T anElement) {
this.anElement = anElement;
}
public Node<T> getNext() {
return next;
}
public void setNext(Node<T> next) {
this.next = next;
}
public Node<T> getPrevious() {
return previous;
}
public void setPrevious(Node<T> previous) {
this.previous = previous;
}
#Override
public String toString() {
return "MyNode{" + "anElement=" + anElement + ", next=" + next + '}';
}
public void insertAfter(T nextData) {
if (nextData == null) {
return;
}
Node s = new Node(nextData);
s.setNext(next);
s.setPrevious(this);
if (next != null) {
next.setPrevious(s);
}
next = s;
}
public void insertBefore(T data) {
if (data == null) {
return;
}
Node s = new Node(data);
s.setNext(this);
s.setPrevious(previous);
if (previous != null) {
previous.setNext(s);
}
previous = s;
}
}
this is the load file class :
public class LoadingMovies {
private static final int size = 127;
private static HashMap<String, Movies> hash = new HashMap(size);
public static void loadMovies(String filename) {
String split = ","; //split with comma
try {
Scanner in = new Scanner(new File(filename));
String wordIn;
//List<Movies> linked = new List<>();
while (in.hasNextLine()) {
wordIn = in.nextLine();
String splitter[] = wordIn.split(split);
String movieTitle = splitter[0];
String movieGenre = splitter[1];
String ageRating = splitter[2];
double scoreRating = Double.parseDouble(splitter[3]);
Movies movie = new Movies();
movie.setTitle(movieTitle);
movie.setGenre(movieGenre);
movie.setAgeRating(ageRating);
movie.setScoreRating(scoreRating);
hash.find(movie.getGenre());
hash.insert(movie.getGenre(), movie);
hash.display();
}
} catch (FileNotFoundException e) {
System.out.println("Exception occured in the loadMovies() method in the Loadingovies class");
}
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String filename = input.next();
loadMovies(filename);
}
this is the hash map method:
public class HashMap<KeyType,DataType>
{
private int count;
private int size;
private List<HashEntry<KeyType,DataType>> [] table;
public HashMap() {
}
public HashMap(int num)
{
size = num;
table = new List[num];
for(int i = 0; i < num; i++){
table[i] = new List<HashEntry<KeyType,DataType>>();
}
}
public void insert(KeyType key, DataType data){
if(key != null && data != null){
int hash = key.hashCode() % size;
HashEntry<KeyType, DataType> obj = new HashEntry(key, data);
table[hash].append(obj);
count++;
}
}
public void display(){
for(int i = 0 ; i < size; i++){
System.out.println("tables" + i + " ");
table[i].display();
}
}
public DataType find(KeyType key){
int hash = key.hashCode() % size;
List<HashEntry<KeyType,DataType>> list = table[hash];
ListIterator <HashEntry<KeyType, DataType>> iter = list.getIterator();
while(iter.isValid()){
if(iter.item().getKey().equals(key)){
return iter.item().getData();
}
iter.advance();
}
return null;
}
public void remove(KeyType key){
int hash = key.hashCode() % size;
List<HashEntry<KeyType,DataType>> list = table[hash];
ListIterator <HashEntry<KeyType, DataType>> iter = list.getIterator();
while(iter.isValid()){
if(iter.item().getKey().equals(key)){
list.remove(iter);
}
iter.advance();
}
}
}
and this is what i have for movie class:
public class Movies {
private String title;
private String genre;
private String ageRating;
private double scoreRating;
public Movies() {
title = "";
genre = "";
ageRating = "";
scoreRating = 0;
}
public Movies(String title, String genre, String ageRating, double scoreRating) {
this.title = title;
this.genre = genre;
this.ageRating = ageRating;
this.scoreRating = scoreRating;
}
public String getTitle() {
return title;
}
public String getGenre() {
return genre;
}
public String getAgeRating() {
return ageRating;
}
public double getScoreRating() {
return scoreRating;
}
public void setTitle(String title) {
this.title = title;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setAgeRating(String ageRating) {
this.ageRating = ageRating;
}
public void setScoreRating(double scoreRating) {
this.scoreRating = scoreRating;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Movies other = (Movies) obj;
if (!Objects.equals(this.title, other.title)) {
return false;
}
if (!Objects.equals(this.genre, other.genre)) {
return false;
}
if (!Objects.equals(this.ageRating, other.ageRating)) {
return false;
}
if (Double.doubleToLongBits(this.scoreRating) != Double.doubleToLongBits(other.scoreRating)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 11;
hash = (int) ((hash * 10) + scoreRating);
if (this.title != null) {
hash = (hash * 10) + title.hashCode();
}
if (this.genre != null) {
hash = (hash * 10) + genre.hashCode();
}
if (this.ageRating != null) {
hash = (hash * 10) + ageRating.hashCode();
}
return hash;
}
#Override
public String toString() {
String statement = "Movie Title:" + title + "\n" + "Movie Genre:" + genre + "\n" + "Age Rating: " + ageRating + "\n" + "User Score: " + scoreRating + "\n";
return statement;
}
what am i doing wrong please :(
i get null pointer exceptions arrayoutofboundexceptions
some movies printing and i get loads of tables thatare null :'(
The problem here is in mapping objects to buckets. This line of code...
int hash = key.hashCode() % size;
is capable of producing a negative value. key.hashCode() can be a negative number, and the result of the % operator on a negative number is a negative number. That's what causes your ArrayIndexOutOfBounds exception. The simplest solution is to use the absolute value of the hashCode...
int hash = Math.abs(key.hashCode()) % size;
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.