I'm trying to implement a save/load function for a game I'm developing. Basically, I have a main class which performs all the rendering and updates a game state object (the game state object holds the player, enemies, and their respective positions, speeds, etc). So I thought I would just save the game state object to a file usingObjectOutputStream
and load with ObjectInputStream
. The saving/loading seems to work fine, until the point where I perform an if-statement on a String field in the player class. I have remade the code as short possible to reproduce the strange behaviour.
The player class:
import java.io.Serializable;
public class Player implements Serializable
{
/**
*
*/
private static final long serialVersionUID = -5933597609049497854L;
private String type;
public Player()
{
type = "evil";
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
}
The Main class:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Main
{
private Player player;
public Main()
{
player = new Player();
System.out.println("player.getType(): ");
System.out.println(player.getType());
System.out.println("player.getType() == evil: ");
System.out.println(player.getType() == "evil");
saveGame();
loadGame();
System.out.println("player.getType(): ");
System.out.println(player.getType());
System.out.println("player.getType() == evil: ");
System.out.println(player.getType() == "evil");
}
public static void main(String[] Args)
{
new Main();
}
private void saveGame()
{
try
{
FileOutputStream out = new FileOutputStream("save");
ObjectOutputStream objectOut = new ObjectOutputStream(out);
objectOut.writeObject(player);
objectOut.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
private void loadGame()
{
try
{
FileInputStream fin = new FileInputStream("save");
ObjectInputStream objectIn = new ObjectInputStream(fin);
player = null;
player = (Player) objectIn.readObject();
objectIn.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
}
I recieve the following output from the program:
player.getType():
evil
player.getType() == evil:
true
player.getType():
evil
player.getType() == evil:
false
Why is the field type
not recognized as "evil"?