Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Hashtable overwrites existing key with new key during 'put'
    primarykey
    data
    text
    <p>I am trying to add entries to an hashtable in Java using Eclipse. During the put operation, only one of the key gets overwriten by a new key and value. The count of the hashtable is maintained properly but one of the (key,value) pair is lost.</p> <p>Here is my sample code:</p> <pre><code>ArrayList&lt;Double&gt; list; Hashtable&lt;Val,ArrayList&lt;Double&gt;&gt; numbers = new Hashtable&lt;Val,ArrayList&lt;Double&gt;&gt;(); while((line = brMyHashval.readLine()) != null) { if(!(line.isEmpty())) { String[] temp; temp = line.split(" "); eDouble = Double.parseDouble(temp[2].toString()); Val key = new Val(Double.parseDouble(temp[0].toString()) ,Double.parseDouble(temp[1].toString()) ); if(!(numbers.containsKey(key))) { list = new ArrayList&lt;Double&gt;(); numbers.put(key, list); } else { list = numbers.get(key); } list.add(eDouble); } } </code></pre> <p>I have used to inbuilt 'hashcode' and 'equals' method in eclipse for comparing class objects.</p> <p>Input Text File:</p> <pre><code>1.0 2.0 9.0 3.0 4.0 9.0 5.0 6.0 9.0 1.0 2.0 8.0 5.0 6.0 8.0 1.0 2.0 7.0 **7.0 8.0 7.0** // After this point a new hash entry gets added for key(7,8), But key (1,2) get deleted from the hashtable, though count gets increased to 4. 3.0 4.0 7.0 5.0 6.0 10.0 1.0 2.0 10.0 1.0 3.0 10.0 1.0 4.0 10.0 </code></pre> <p>Why does the key get deleted at that specific instant.?</p> <p>[edit] hashcode and equals: I used eclipse to automatically import these methods // (x,y) is (a,b)</p> <pre><code> class Val { double x; double y; Val(double X, double Y) { x = X; y = Y; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits(x); result = prime * result + (int) (temp ^ (temp &gt;&gt;&gt; 32)); temp = Double.doubleToLongBits(y); result = prime * result + (int) (temp ^ (temp &gt;&gt;&gt; 32)); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Val other = (Val) obj; if (Double.doubleToLongBits(x) != Double.doubleToLongBits(other.x)) return false; if (Double.doubleToLongBits(y) != Double.doubleToLongBits(other.y)) return false; return true; } </code></pre> <p>}</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload