Advertisement
heavenriver

2011_03_04.java (ex. 2)

Dec 31st, 2012
247
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.88 KB | None | 0 0
  1. // Esame del 4 marzo 2011, esercizio 2
  2. // Ricordarsi di specificare sempre, nei commenti al codice, l'utilità di ogni metodo.
  3.  
  4. interface Map<K, V>
  5.     {
  6.     public static final int HORNER_Z = 33;
  7.     public Entry<K, V> get(K key);
  8.     public Entry<K, V> put(K key, V value);
  9.     public Entry<K, V> remove(K key);
  10.     public int size();
  11.     public Collection<K> keys();
  12.     public Collection<V> values();
  13.     public Collection<Entry<K, V>> entries();
  14.     public int hash(K key);
  15.     }
  16.  
  17. interface Entry<K, V>
  18.     {
  19.     K key;
  20.     V value;
  21.     public Entry(K key, V value);
  22.     public K getKey();
  23.     public V getValue();
  24.     }
  25.  
  26. public int hash(String key) // Costo computazionale non richiesto
  27.     {
  28.     int pos = 0;
  29.     for(int i = 0; i < key.length(); i++)
  30.         pos += key.charAt(i) * Math.pow(HORNER_Z, i);
  31.     return pos;
  32.     }
  33.  
  34. // Il metodo assume una variabile d'istanza private Entry<String, String>[] entries nella classe della mappa!
  35. public Entry<String, String> put(String key, String value) throws Exception // Costo computazionale non richiesto
  36.     {
  37.     int pos = hash(key);
  38.     if(pos > entries.length) pos = pos % entries.length;
  39.     boolean done = false;
  40.     for(int i = 0; i < size(); i++)
  41.         {
  42.         if(pos + i < entries.length)
  43.             {
  44.             if(entries[pos + i] == null)
  45.                 {
  46.                 entries[pos + i] = new Entry<String, String>(key, value);
  47.                 done = true;
  48.                 return entries[pos + i];
  49.                 }
  50.             }
  51.         else
  52.             {
  53.             if(entries[(pos + i) % entries.length] == null)
  54.                 {
  55.                 entries[(pos + i) % entries.length] = new Entry<String, String>(key, value);
  56.                 done = true;
  57.                 return entries[(pos + i) % entries.length];
  58.                 }
  59.             }
  60.         }
  61.     if(!done) throw new Exception("Element insertion failed");
  62.     }
  63.  
  64. public Entry<String, String> remove(K key) // Costo computazionale non richiesto
  65.     {
  66.     int pos = hash(key);
  67.     if(pos > entries.length) pos = pos % entries.length;
  68.     Entry<String, String> out = entries[pos];
  69.     entries[pos] = null;
  70.     return out;
  71.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement