views:

249

answers:

3

Hi ..

I have a problem in Java hashtable serialization that seems illogical to me but i am not able to find out the error in the logic i am using. Here is what i am doing,

Hashtable sspsrpData = new Hashtable();
for(int i=0;i<Constants.secondayStructures.length;i++) {
    SecondaryStructures ss = (SecondaryStructures)(data.get(Constants.secondayStructures[i]));
    sspsrpData.put(Constants.secondayStructures[i], new SecStrucPSRP(ss.getSecStruct(),ss.getLengthCounts())); 
}
 FileOutputStream fos = null;
 ObjectOutputStream out = null;
    fos = new FileOutputStream(Constants.sspsrpData);
    out = new ObjectOutputStream(fos);
    out.writeObject(sspsrpData);

This piece of code should put 3 key-value pairs in the hashtable and also should serialize the thus formed hashtable. Now when i am trying to retrive them back in another program by this piece of code:

FileInputStream fis = null;
ObjectInputStream in = null;
fis = new FileInputStream(Constants.sspsrpData);
in = new ObjectInputStream(fis);
ssPsrp = (Hashtable)in.readObject();

The resulting hashtable has only 2 key-value pairs. Though the count in the hashtable says 3 i can only see 2 key value pairs in the hashtable. I do not understand whats going wrong!!

Can somebody point out where am i going wrong?

Thanks and Good day, Santhosh

A: 

Are the objects in the hashtable serializable?

Allan
A: 

Yes .. The strange thing all the 3 key-value pairs are identical (String - SecStrucPSRP object). All the objects are serializable. Only 2 of them are accessible while deserializing the hashtable ..

+1  A: 

Maybe Constants.secondayStructures[0] .equals( Constants.secondayStructures[1] ) or Constants.secondayStructures[1] .equals( Constants.secondayStructures[2] )

Try a sspsrpData.size() before serialize your object, to be sure it has the good size before serializing.

Lastnico
I too thought so and started debugging .. Did not find a solution but an interesting observation .. One of the keys is getting replaced while adding the key, so if the initial hashtable has 10 values to be filled and the first addition was at 6 and the next addition was at 4 the last addition was being added again at 4 .. I dont know how is that happening. The keys are different for sure. I tried it using hashmap instead of hashtable and it works perfectly fine .. Thnaks for replying .. If someone faces the same issue, i would like to know if they have same debugging symptoms ..
It is normal that several different keys get stored at the same position, the position is determined by a hash function. When several keys are stored at the same position, the entries (key+value) are chained. To get a value given a key, the key is hashed to find what position to look at and then the key is compared (with equals) with the key at the given position. So hashcode and equals have to be consistent and also stable over time...
pgras