I have code for Testing Serialization with One Static Member.
Here Is the Car Class
public class Car implements Serializable {
private String number;
private String color;
private String model;
static int y = 23;
public boolean equals(Object object)
{
System.out.println("Equals Called...");
if(object instanceof Car)
{
Car car = (Car) object;
if(car.getNumber() == this.number)
{
return true;
}
}
return false;
}
public String toString()
{
System.out.println("ToString Called...");
return "Number : "+this.number+" Color : "+this.color+" Model : "+this.model+" Y : "+this.y;
}
public int hashCode()
{
return this.y * 23;
}
Getters And Setters
}
And Here is My Main Class
public static void main(String args[])
{
Car car1 = new Car();
car1.setColor("red");
car1.setModel("23023");
car1.setNumber("1212");
System.out.println(car1.toString());
Car car2 = new Car();
car2.setColor("red");
car2.setModel("23023");
car2.setNumber("1212");
System.out.println(car2.toString());
Map<Car, String> map = new HashMap<Car, String>();
map.put(car1, "Kshitij_1");
System.out.println("Map : "+map.toString());
System.out.println(map.get(car2));
System.out.println(car2.getY());
System.out.println("---------------------------------------------Before");
try
{
FileOutputStream fout = new FileOutputStream("D://map.ser");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fout);
objectOutputStream.writeObject(map);
objectOutputStream.close();
FileInputStream fin = new FileInputStream("D://map.ser");
ObjectInputStream inputStream = new ObjectInputStream(fin);
map = (Map<Car, String>) inputStream.readObject();
inputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
System.out.println("Map : "+map.toString());
System.out.println(map.get(car2));
System.out.println(car2.getY());
System.out.println("---------------------------------------------After");
}
My Expectation is That result should be Same Before And After. But I am Getting Null
Output
ToString Called...
Map : {Number : 1212 Color : red Model : 23023 Y : 23=Kshitij_1}
Equals Called...
Kshitij_1
23
---------------------------------------------Before
ToString Called...
Map : {Number : 1212 Color : red Model : 23023 Y : 23=Kshitij_1}
Equals Called...
null
23
---------------------------------------------After
at
System.out.println(map.get(car2));
According to the serialization Rules in Deserializing process the static variable will be initialize to default value. If its initialize with 23 than why its not able to find Object from HashMap?