Autor Tema: java.lang.NullPointerException Java por no inicializar objetos intentas acceder  (Leído 2376 veces)

r2montero

  • Sin experiencia
  • *
  • Mensajes: 40
    • Ver Perfil
Hola amigos!

En un ejercicio de clase nos pidieron programar un Hashtable "a pie", es decir, emular el funcionamiento del Hashtable.

El problema es que no se como resolver la NullPointerException que me esta lanzando la linea 98 de la clase Hashtable.

Les dejo el código para ver si me pueden ayudar y/o dar alguna sugerencia...

Gracias de antemano!

Clase Table.
Código: [Seleccionar]
/**
 * Class Table.
 * To create Table type objects with a key and its corresponding value.
 *
 * @author r2montero.
 * @version 1.0.
 */
public class Table {

    //Atributes
    /**
     * The corresponding key.
     */
    private Object key;

    /**
     * The value linked to the key.
     */
    private Object value;

    /**
     * Default constructor.
     */
    public Table() {
        setKey(null);
        setValue(null);
    }

    /**
     * Constructor with custom key and value.
     *
     * @param key - the corresponding key.
     * @param value - the corresponding value.
     */
    public Table(Object key, Object value) {
        setKey(key);
        setValue(value);
    }

    /**
     *
     * @return
     */
    public Object getValue() {
        return value;
    }

    /**
     *
     * @return
     */
    public Object getKey() {
        return key;
    }

    /**
     *
     * @param value
     */
    public void setValue(Object value) {
        this.value = value;
    }

    /**
     *
     * @param key
     */
    public void setKey(Object key) {
        this.key = key;
    }

}

Clase Hashtable.
Código: [Seleccionar]
/**
 * Class Hashtable
 *
 * This class lets you create tables arrays where you can link keys to values.
 *
 * @author r2montero.
 * @version 1.0.
 */
public class Hashtable {
    //Atributes

    /**
     * Array size.
     */
    private int size;
    /**
     * Object's table array.
     */
    private Table[] hashtable;

    /**
     * Constructs a new, empty hashtable with a default initial capacity of 11.
     */
    public Hashtable() {
        size = 11;
        hashtable = new Table[size];
    }

    /**
     * Constructs a new, empty hashtable with the specified initial capacity.
     *
     * @param size - the initial capacity of the hashtable. Trhrows
     * IllegalArgumentException - if the initial capacity is less than zero.
     */
    public Hashtable(int size) {
        if (size <= 0) {
            throw new IllegalArgumentException();
        } else {
            this.size = size;
            hashtable = new Table[size];
        }
    }

    /**
     * If needed, it creates a new array with space for one more element, and
     * copy into it the elements of the smaller array.
     *
     * @return the new hashtable array.
     */
    private Table[] incrementSize() {
        Table[] tempHashtable = new Table[length() + 1];
        if (isFull()) {
            for (int counter = 0; counter < length(); counter++) {
                tempHashtable[counter] = hashtable[counter];
            }
            return tempHashtable;
        }
        return hashtable;
    }

    /**
     * Check if the array is full.
     *
     * @return true if full, false if not.
     */
    private boolean isFull() {
        try {
            for (int counter = 0; counter < length(); counter++) {
                if (hashtable[counter].getKey() != null && counter == length() - 1) {
                    return true;
                }
            }
        } catch (Exception NullPointerException) {
            return false;
        }
        return false;
    }

    /**
     * Link the specified key to the specified value in this hashtable. Neither
     * the key nor the value can be null.
     *
     * @param key - the hashtable key.
     * @param value - the value. Throws NullPointerException - if the key or
     * value is null.
     */
    public void put(Object key, Object value) {
        if (key != null && value != null) {
            hashtable = incrementSize();
            for (int counter = 0; counter < length(); counter++) {
                try {
                    if (hashtable[counter].getKey() == null && !containsKey(key)) {
                        hashtable[counter].setKey(key);
                        hashtable[counter].setValue(value);
                    }
                } catch (Exception NullPointerException) {
                    hashtable[counter].setKey(key);
                    hashtable[counter].setValue(value);
                }
            }
        } else {
            throw new NullPointerException();
        }
    }

    /**
     * Removes the key (and its corresponding value) from this hashtable.
     *
     * @param key - the key that needs to be removed. Throws
     * NullPointerException - if the key is null
     */
    public void remove(Object key) {
        if (key == null) {
            throw new NullPointerException();
        } else {
            for (int counter = 0; counter < length(); counter++) {
                if (hashtable[counter].getKey() == key) {
                    hashtable[counter].setKey(null);
                    hashtable[counter].setValue(null);
                }
            }
        }
    }

    /**
     * Remove all the keys and his linked values.
     */
    public void clear() {
        for (int counter = 0; counter < length(); counter++) {
            hashtable[counter].setKey(null);
            hashtable[counter].setValue(null);
        }
    }

    /**
     * Tests if the specified object is a key in this hashtable.
     *
     * @param key - possible key.
     * @return true if the key is in hashtable, false if not. Throws
     * NullPointerException - if the key is null.
     */
    public boolean containsKey(Object key) {
        if (key == null) {
            throw new NullPointerException();
        } else {
            for (int counter = 0; counter < length(); counter++) {
                if (hashtable[counter].getKey().equals(key)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Tests if the specified object is a value in this hashtable.
     *
     * @param value - possible value.
     * @return true if the value is in hashtable, false if not.
     */
    public boolean containsValue(Object value) {
        for (int counter = 0; counter < length(); counter++) {
            if (hashtable[counter].getValue().equals(value)) {
                return true;
            }
        }
        return false;
    }

    /**
     * Check if the array is empty.
     *
     * @return true if empty, false if not.
     */
    public boolean isEmpty() {
        if (size() == 0) {
            return true;
        }
        return false;
    }

    /**
     * Return the hashtable length.
     *
     * @return the length.
     */
    public int length() {
        return hashtable.length;
    }

    /**
     * Returns the number of keys in the hashtable.
     *
     * @return the number of keys in this hashtable.
     */
    public int size() {
        int hashSize = 0;
        try {
            for (int counter = 0; counter < hashtable.length; counter++) {
                if (hashtable[counter].getKey() != null) {
                    hashSize++;
                }
            }
        } catch (Exception e) {
            return hashSize;
        }
        return hashSize;
    }

    /**
     * @param key - the hashtable key. Returns the value to which the specified
     * key is linked. Throws NullPointerException - if the specified key is
     * null.
   *
     */
    public Object get(Object key) {
        Object value = "El campo " + key + " no contiene ningun valor.";
        if (key == null) {
            throw new NullPointerException();
        } else {
            for (int counter = 0; counter < hashtable.length; counter++) {
                if (hashtable[counter].getKey().equals(key)) {
                    if (hashtable[counter].getValue() != null) {
                        value = hashtable[counter].getValue();
                    }
                }
            }
        }

        return value;
    }

    /**
     * Returns a string representation of this Hashtable.
     *
     * @return a string representation of this hashtable.
     */
    @Override
    public String toString() {
        String text = null;
        for (int counter = 0; counter < length(); counter++) {
            text += hashtable[counter].getKey() + " " + hashtable[counter].getValue() + "\n";
        }
        return text;
    }
}

Clase Main.
Código: [Seleccionar]
public class Main {

    public static void main(String[] args) {
        Hashtable hashtable11 = new Hashtable();
        Hashtable hashtable3 = new Hashtable(3);

        hashtable11.put(1, "Navas");
        hashtable11.put(19, "Miller");
        hashtable11.put(6, "Duarte");
        hashtable11.put(3, "Gonzalez");
        hashtable11.put(8, "Diaz");
        hashtable11.put(5, "Borges");
        hashtable11.put(17, "Tejeda");
        hashtable11.put(16, "Gamboa");
        hashtable11.put(14, "Brenes");
        hashtable11.put(10, "Ruiz");
        hashtable11.put(9, "Campbell");

        System.out.println("Alineacion de C.R. vrs. Inglaterra en Brasil 2014\n" + hashtable11.toString());

    }
}
« Última modificación: 28 de Agosto 2016, 22:41 por Ogramar »

Ogramar

  • Moderador Global
  • Experto
  • *******
  • Mensajes: 2659
    • Ver Perfil
Buenas, el código es muy largo y con tanto código se hace difícil depurar. No estoy seguro pero intento darte una orientación

En el constructor de la clase Hashtable tienes esto:

Código: [Seleccionar]
    public Hashtable() {
        size = 11;
        hashtable = new Table[size];
        System.out.println ("que ocurre aquí " + hashtable);
        System.out.println ("que ocurre aquí 2 " + hashtable[0]);
       
       
    }

Si te fijas ahí lo que haces es declarar un objeto que es un array de elementos table. Por tanto hashtable ya es un objeto y puedes acceder a él.

Sin embargo, cada uno de los elementos de hashtable es un objeto de tipo Table y cada uno de esos objetos no ha sido inicializado, por tanto si tú intentas acceder a hashtable[0] por ejemplo te devuelve un java.lang.NullPointerException

¿Por qué? Porque ese objeto no ha sido inicializado.

Ese error es justamente el que te tira en el método put en la línea

hashtable[counter].getKey()

Ahí intentas acceder a hashtable[0] y te tira el java.lang.NullPointerException

Podrías probar a recorrer el array de elementos en el constructor e inicializar cada uno de ellos con el constructor de Table

Salu2

r2montero

  • Sin experiencia
  • *
  • Mensajes: 40
    • Ver Perfil
Muchas gracias por la ayuda!

De hecho el problema era ese. Estaba creando el arreglo, pero no estaba inicializando cada celda con un Table antes de intentar acceder a ellos!

Saludos!

 

Sobre la educación, sólo puedo decir que es el tema más importante en el que nosotros, como pueblo, debemos involucrarnos.

Abraham Lincoln (1808-1865) Presidente estadounidense.

aprenderaprogramar.com: Desde 2006 comprometidos con la didáctica y divulgación de la programación

Preguntas y respuestas

¿Cómo establecer o cambiar la imagen asociada (avatar) de usuario?
  1. Inicia sesión con tu nombre de usuario y contraseña.
  2. Pulsa en perfil --> perfil del foro
  3. Elige la imagen personalizada que quieras usar. Puedes escogerla de una galería de imágenes o subirla desde tu ordenador.
  4. En la parte final de la página pulsa el botón "cambiar perfil".