I am new to Java and encountered this problem: I am learning how to save object state to a file and I got stuck with passing an array to the constructor. I believe that the problem is the base class with the constructor but I am not sure.
here is my Hero class:
import java.io.Serializable;
public class Hero implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private int power;
private String type;
private String[] wepons;
public int getPower() {
return power;
}
public void setPower(int power) {
this.power = power;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String[] getWepons() {
return wepons;
}
public void setWepons(String[] wepons) {
this.wepons = wepons;
}
public Hero(int powerH, String typeH, String[] weponsH) {
this.power = powerH;
this.type = typeH;
this.wepons = weponsH;
}
}
and here is class which I try to use to save the object state:
import java.io.*;
public class SaveGame {
public static void main(String[] args) {
Hero hero1 = new Hero(50, "Elf", new String[] {"bow", "short sword", "powder"});
try{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Game.ser"));
os.writeObject(hero1);
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
ObjectInputStream is;
try {
is = new ObjectInputStream(new FileInputStream("Game.ser"));
Hero p1N = (Hero) is.readObject();
System.out.println(p1N.getPower() + " " + p1N.getType() + " " + p1N.getWepons());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
Can you tell me and explain what am I doing wrong. Do I really need setters and getters in my Hero class and I have the feeling that I am using them incorrectly.
My problem was that when I tried to print out the Hero's parameters I got content of the array instead of string representation of the array. Thanks to user2336315 I know now that i should use Arrays.toString method when printing content of an array