【问题标题】:Serializing an Arraylist<CustomObject>序列化 Arraylist<CustomObject>
【发布时间】:2016-09-19 21:46:14
【问题描述】:

我创建了一个名为“Item”的对象,我想序列化一个包含 Items 的 ArrayList。我的程序与ArrayList&lt;String&gt; 完美配合,但不适用于ArrayList&lt;Item&gt;。我相信这与我的对象有关。这里是:

public class Item implements Serializable{

private static String name;
private static BufferedImage picture;
private static boolean craftable;
private static Item[][] craftTable;
private static boolean smeltable;
private static Item smelt_ancestor;
private static Item smelt_descendant;

public Item(String name, boolean craftable, boolean smeltable){
    this.name = name;
    this.craftable = craftable;
    if(craftable){
        craftTable = new Item[3][3];
    }else{
        craftTable = null;
    }
    this.picture = null;
    this.smeltable = smeltable;
    this.smelt_ancestor = null;
    this.smelt_descendant = null;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name=name;
}

public BufferedImage getPicture(){
    return picture;
}

public boolean setPicture(){
    boolean verify = false;
    String pictureName = name.replaceAll("\\s+","");
    String newNamePng = pictureName + ".png";
    String newNameJpg = pictureName + ".jpg";
    File imagePng = new File(newNamePng);
    File imageJpg = new File(newNameJpg);
    if(imagePng.exists()){
        return true;
    }else if(imageJpg.exists()){
        return true;
    }else{
        return false;
    }
}

public boolean getCraftable(){
    return craftable;
}

public void setCraftable(boolean value){

    this.craftable = value;
}

public boolean setCraftTable(Item[][] table){
    if(this.craftable==true){
        craftTable = table;
        return true;
    }else{
        return false;
    }

}

public Item[][] getCraftTable(){
    return craftTable;
}

public boolean getSmeltable(){
    return smeltable;
}

public void setSmeltable(boolean value){
    smeltable = value;
}

public Item getAncestor(){
    return smelt_ancestor;
}

public void setAncestor(Item ancestor){
    smelt_ancestor = ancestor;
}

public Item getDescendant(){
    return smelt_descendant;
}

public void setDescendant(Item des){
    smelt_descendant = des;
}

public String toString(){
    return name;
}

忽略导入,我在其他我省略的方法中使用它们,因为它们工作得很好。 Object 有什么问题会阻止它被正确序列化吗?

【问题讨论】:

标签: java serialization arraylist


【解决方案1】:

静态变量不序列化。看起来您可能希望这些是非静态实例变量。

【讨论】:

    【解决方案2】:

    定义的序列化应用于对象而不是类。 它复制要通过网络或流传输或要存储的对象的状态。 您对静态变量的使用使它们成为类变量,因此它们对对象的状态没有贡献。首先要做的是使它们成为非静态的。

    这给我们留下了你的类,它已经是可序列化的,ArrayList 也是如此。您可以使用 ObjectInputStream 和 ObjectOutputStream 对它们进行序列化和反序列化,并确保在反序列化端的类路径中具有相同的类。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-08
      • 2014-03-24
      • 2014-11-20
      相关资源
      最近更新 更多