Problem with AVL tree vector

Asked

Viewed 84 times

2

Good afternoon!

I am making a hash table and for this I am trying to create an AVL tree vector. The problem is that when I try to insert a value in any tree of this vector is giving the exception "Nullpointerexception". Could someone tell me where I’m going wrong?

I am very grateful.

public class Hashing {
ArvoreAvl[] lAVL;
int mod;

public Hashing(int tamanho){
    lAVL = new ArvoreAvl[tamanho];
    mod = tamanho;        
}

public void inserir(int valor){
    int rest = valor % mod;
    for(int x = 1; x < lAVL.length; x++){
        if(x == rest){
            // Está dando java.lang.NullPointerException na linha abaixo
            lAVL[x].inserir(valor);
        }
    }
}

public void remover(int valor){
    int rest = valor % mod;

    for(int x = 0; x < mod; x++){
        if(x == rest){
            lAVL[x].remover(valor);
        }
    }
}

public void imprimir(){
   for(int x = 0; x < lAVL.length; x++){
        lAVL[x].inorder();
        System.out.println();
   } 
}

1 answer

5


You’re forgetting to instantiate the vector lAVL[x] on that line add the instance:

if(x == rest){
    lAVL[x] = new ArvoreAvl();
    lAVL[x].inserir(valor);
}

In your class constructor, you are setting the size of your vector, but you are not instantiating the class ArvoreAVL for the vector positions. Same thing I did:

ClasseQualquer[] classe = new ClasseQualquer[10];

This just defined the size of my vector in the class ClasseQualquer then for me instanciar would have to put inside a for:

for(int i = 0; i < 20; i++)
{
    classe[i] = new ClasseQualquer();
}
  • But I’m doing it in the class builder.

  • No no, in the class constructor you are not instantiating hehe you have to instantiate each node of your vector, I will edit the answer if you can understand better.

  • Ahh, now I understand Matheus. Thank you very much for your help. :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.