diff --git a/src/Aufgabe5Test.java b/src/Aufgabe5Test.java index cd67d81..c425e6b 100644 --- a/src/Aufgabe5Test.java +++ b/src/Aufgabe5Test.java @@ -78,4 +78,19 @@ public class Aufgabe5Test { assertEquals(hashCode2, map.hashCode()); assertNotEquals(hashCode1, hashCode2); } + + @Test + public void testDelKey() { + MassiveForceHashMap map = new MassiveForceHashMap(); + NamedBody sun1 = new NamedBody(SolSystem4.SUN_NAMED); + NamedBody earth1 = new NamedBody(SolSystem4.EARTH_NAMED); + NamedBody moon1 = new NamedBody(SolSystem4.MOON_NAMED); + map.put(sun1, new Vector3()); + map.put(earth1, new Vector3()); + map.put(moon1, new Vector3()); + assertNotNull(map.get(sun1)); + assertNotNull(map.delete(sun1)); + assertNull(map.get(sun1)); + assertNull(map.delete(sun1)); + } } diff --git a/src/MassiveForceHashMap.java b/src/MassiveForceHashMap.java index 27cbe4e..878c735 100644 --- a/src/MassiveForceHashMap.java +++ b/src/MassiveForceHashMap.java @@ -65,16 +65,36 @@ public class MassiveForceHashMap { * Precondition: key != null. */ public Vector3 get(Massive key) { + int pos = find(key); + return (pos == -1) ? null : values[pos]; + } + + private int find(Massive key) { int idx = ((key.hashCode() % keys.length) + keys.length) % keys.length; for (int i = 0; i < keys.length; i++) { int pos = (idx + i) % keys.length; if (keys[pos] == null) { break; } else if (keys[pos].equals(key)) { - return values[pos]; + return pos; } } - return null; + return -1; + } + + /** + * Deletes the mapping for the specified key from this map if present. + * Returns the previous value associated with key, or null if there was + * no mapping for key. + * Precondition: key != null + */ + public Vector3 delete(Massive key) { + int pos = find(key); + if (pos == -1) return null; + + Vector3 val = values[pos]; + values[pos] = null; + return val; } /**