Problem with AVL tree vector

2

Good afternoon!

I'm doing a hash table and for this I'm trying to create an AVL Tree vector. The problem is that when I try to insert a value into any tree of this vector it is giving the "NullPointerException" exception. Could someone tell me where I'm 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();
   } 
}
    
asked by anonymous 02.10.2017 / 20:46

1 answer

5

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

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

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

ClasseQualquer[] classe = new ClasseQualquer[10];

This just set the size of my vector in class ClasseQualquer so for me to instantiate would have to put inside a for:

for(int i = 0; i < 20; i++)
{
    classe[i] = new ClasseQualquer();
}
    
02.10.2017 / 20:51