0

I have a PaymentPreference class which has a hashmap to store all paymentmethods opted by consumer while he created his profile. This PaymentMethod is another class whose object are stored in this PaymentPreference hashmap as key and a Boolean object as its value. This is all done this way for some specific purpose.

Comming to the issue, i have a case where i need to serialize this PaymentPreference which has this Hashmap with PaymentMethod object as key. So, before serialize , i check if a specific key is present in Hashmap using containsKey and it returns true. After that i went with serialization. But, when i deserialize the PaymentPreference object and try to check if same key is present in hashmap using the contains key method, i am getting false. This looked strange as i knew that the key is there in Hashmap. But somehow, after serialization, i was unable to find a match for that key using containsKey method.

Since it is all about matching an object, i tried printing the hash code values of the hashmap keys before and after serialization and there it is. There is a difference in the hashcode value of the hashmap key before and after serialization. This is the reason my containsKey method not returning true after deserialization. I have no idea why it is happening like this. I haven't done much work on serialization, it is just now for some specific case i had to do this. I dont find any convincing answer in already existing threads on this. Can somebody shed some light on why this is happening and what should i do to prevent this ?

PFB my classes

PaymentMethods Class

public class PaymentMethods implements java.io.Serializable{



/**
 * 
 */
private static final long serialVersionUID = 3398741949646654368L;


private String paymentMethod;


public static final PaymentMethods CASH = new PaymentMethods("CashPayment");    
public static final PaymentMethods BITCOIN = new PaymentMethods("BitCoin");
public static final PaymentMethods CARD = new PaymentMethods("Card");
public static final PaymentMethods CHEQUE= new PaymentMethods("Cheque");
public static final PaymentMethods MPAY= new PaymentMethods("MobPay");
public static final PaymentMethods PAYME= new PaymentMethods("PayMe");

public PaymentMethods(String paymentMethod) {
    this.paymentMethod=paymentMethod;

}

/**
 * @return the paymentMethod
 */
public String getPaymentMethod() {
    return this.paymentMethod;
}

}

PaymentPreferences Class

import java.util.HashMap;
import java.util.Map;

public class PaymentPreferences implements java.io.Serializable {


/**
 * 
 */
private static final long serialVersionUID = 7475358849630530148L;


//preferences with on/off 
private Map<PaymentMethods,Boolean> paymentPreferenceMap = new HashMap<PaymentMethods,Boolean> ();


/**
 * @return the paymentPreferenceMap
 */
public Map<PaymentMethods, Boolean> getPaymentPreferenceMap() {
    return paymentPreferenceMap;
}


public void addSelectedPreferences(PaymentMethods paymentMethod){       

    paymentPreferenceMap.put(paymentMethod, Boolean.TRUE);

}


public boolean isCashPaymentPreferred(PaymentMethods inputPaymentMethod){

    return paymentPreferenceMap.containsKey(inputPaymentMethod);

}


@Override
public String toString() {

    StringBuffer sBuffer = new StringBuffer();

    sBuffer.append("Is CashPayment Preferred ? -> "+isCashPaymentPreferred(PaymentMethods.CASH));

    return sBuffer.toString();

}

}

Class to test Serialize/Deserialize

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Set;

public class TestSerialize {

private PaymentPreferences paymentPreference;

public static void main(String[] args) {

    TestSerialize testObj=new TestSerialize();

    testObj.initializeData();

    testObj.serializeData();

    testObj.deSerializeData();
}

private void deSerializeData() {        

    Object object=null;

    System.out.println("Deserializing ");

    try {
        FileInputStream fis = new FileInputStream("D:\\TestPref.dat");

        ObjectInputStream ois= new ObjectInputStream(fis);

        object = ois.readObject();

        ois.close();

        fis.close();

    } catch (Exception e) {

        e.printStackTrace();
    }



    System.out.println("After Deserialization, Cash Preference check -> "+(PaymentPreferences)object);


    System.out.println("After Deserialization,hash code value for map key ->");

    printHashCodeForKeys(((PaymentPreferences)object));

}


private void serializeData() {

    System.out.println("Before Serialization, Cash Preference check -> "+paymentPreference);

    System.out.println("Before Serialization,hash code value for map key ->");

    printHashCodeForKeys(paymentPreference);
    try {
        FileOutputStream fos = new FileOutputStream("D:\\TestPref.dat");

        ObjectOutputStream ous= new ObjectOutputStream(fos);

        ous.writeObject(paymentPreference);

        ous.close();

        fos.close();

        System.out.println("Serialization done");
        System.out.println();

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}

public void printHashCodeForKeys(PaymentPreferences paymentPreference) {

    Set<PaymentMethods> keySet=paymentPreference.getPaymentPreferenceMap().keySet();

    for(PaymentMethods methodObj:keySet) {

        System.out.println(methodObj.hashCode());
    }

    System.out.println("Hashcode for PaymentMethods.CASH object is "+PaymentMethods.CASH.hashCode());

}

private void initializeData() {

    paymentPreference = new PaymentPreferences();

    paymentPreference.addSelectedPreferences(PaymentMethods.CASH);
}

}

OUTPUT:

Before Serialization, Cash Preference check -> Is CashPayment Preferred ? -> true
Before Serialization,hash code value for map key ->
1096192577
Hashcode for PaymentMethods.CASH object is 1096192577
Serialization done

Deserializing 
After Deserialization, Cash Preference check -> Is CashPayment Preferred ? -> false
After Deserialization,hash code value for map key ->
428583986
Hashcode for PaymentMethods.CASH object is 1096192577
rjb007
  • 11
  • 3
  • 1
    Well, where do you override the `hashCode()` and `equals(Object o)` methods? If you don't do this, then your class defaults to that of the Object class, and this behavior should be expected. Also please be sure to read [What issues should be considered when overriding equals and hashCode in Java?](https://stackoverflow.com/questions/27581/what-issues-should-be-considered-when-overriding-equals-and-hashcode-in-java) – Hovercraft Full Of Eels Jul 13 '18 at 14:24
  • 2
    You need to implement hashCode/equals functions – GotoFinal Jul 13 '18 at 14:25
  • @Hovercraft Full Of Eels Thanks. Wonder why i didnt think about that. Overrided hashcode and equal and the issue is now gone. Thanks again. – rjb007 Jul 13 '18 at 14:53
  • Good deal, and glad it's working – Hovercraft Full Of Eels Jul 13 '18 at 14:55

0 Answers0