Ver Mensaje Individual
  #6 (permalink)  
Antiguo 19/04/2017, 22:53
Avatar de detective_jd
detective_jd
 
Fecha de Ingreso: abril-2011
Ubicación: Salto
Mensajes: 437
Antigüedad: 13 años, 1 mes
Puntos: 6
Respuesta: Implementar TablaHash

Les cuento que encontrando una función hashCode me solucionó un poco el problema:

private int getIndex(Object key) {
return (key.hashCode() & 0x7FFFFFFF) % table.length;
}

pero me dio este resultado:

indice -> 1
indice -> 2
indice -> 3
indice -> 4

cuando tendría que hacer esto:

indice -> 0
indice -> 1
indice -> 2
indice -> 3

No sé si cambiar o agregar cosas en la Pair

Código Java:
Ver original
  1. class Pair<K,V> {
  2.         final K key;
  3.         V value;
  4.         Pair(K k, V v) {
  5.             value = v;
  6.             key = k;
  7.         }
  8.         public final K getKey() {
  9.             return key;
  10.         }
  11.         public final V getValue() {
  12.             return value;
  13.         }
  14.         @Override
  15.         public String toString() {
  16.             return getKey() + "=" + getValue();
  17.         }
  18.     }

o cambiar algo de los métodos para guardar la entrada en mi tablahash

Código Java:
Ver original
  1. public V put(K key, V value) {
  2.         if(key == null){
  3.             return null;
  4.         } else {
  5.             int index = getIndex(key);
  6.             System.out.println("indice -> "+ index);
  7.             Pair<K, V> pair = table[index];
  8.             if (pair != null && (pair.key == key ||  pair.key.equals(key))) {
  9.                 V oldValue = pair.value;
  10.                 pair.value = value;
  11.                 return oldValue;
  12.             }
  13.             setPair(key, value, index);        
  14.             return value;
  15.         }
  16.     }
  17. private int getIndex(Object key) {
  18.        return (key.hashCode() & 0x7FFFFFFF) % table.length;
  19.     }
  20.  
  21.     private void setPair(K key, V value, int index) {
  22.         Pair<K, V> e = table[index];
  23.         while (e != null) {
  24.             index++;
  25.             if (index >= capacity) {
  26.                 table = Arrays.copyOf(table, table.length +1);
  27.                 put(key,value);
  28.                 return;
  29.             }
  30.             e = table[index];
  31.         }
  32.         table[index] = new Pair<>(key, value);
  33.         size++;
  34.     }

Espero sus respuestas y Saludos.