0

鉴于此代码:

public class TestSetup extends Object implements Serializable {
   // ... some data and methods
}
ArrayList SetupArray = new ArrayList<TestSetup>();
// ----------------------------------------------
    public boolean readExternalStorageObjectFile(String filename, Object obj) {
    boolean isOk = true;
    try {
        File path = new File(sDirectoryPath + sTopDirectoryObj, filename);
        FileInputStream out = new FileInputStream(path);
        ObjectInputStream o = new ObjectInputStream(out);
        obj = o.readObject();
        o.close();
    }
    catch(Exception e) {
        Log.e("Exception","Exception occured in reading");
        isOk = false;
    }        
    return isOk;
}

// ----------------------------------------------
public void loadSetups() {
    this.SetupArray.clear();
    this.readExternalStorageObjectFile(SETUPS_FILENAME, this.SetupArray);
}

我希望 loadSetups() 中的 this.SetupArray 包含从 readExternalStorageObjectFile() 读取的现有数组信息,但事实并非如此。

如果我在 readExternalStorageObjectFile() 中放置一个断点,我会看到执行 readObject() 时 obj 确实包含 ArrayList 信息。

但是当它返回到 loadSetups() 时,this.SetupArray 没有;它是空的。

我尝试将 obj 转换为 ArrayList,但结果相同。

4

1 回答 1

1

obj参数是一个指针。如果您重新分配它obj = o.readObject()而不修改引用的数据,您只需将指针重新分配到另一个内存位置。

一个解决方案是让方法返回对象:

ArrayList SetupArray = new ArrayList<TestSetup>();

public Object readExternalStorageObjectFile(String filename) {
    try {
        File path = new File(sDirectoryPath + sTopDirectoryObj, filename);
        FileInputStream out = new FileInputStream(path);
        ObjectInputStream o = new ObjectInputStream(out);
        Object obj = o.readObject();
        o.close();
        return obj;
    }
    catch(Exception e) {
        Log.e("Exception","Exception occured in reading");
        return null;
    }        
}

public void loadSetups() {
    this.SetupArray = (ArrayList) this.readExternalStorageObjectFile(SETUPS_FILENAME);
}
于 2012-08-02T13:53:24.857 回答