质量更好:http://img20.imageshack.us/img20/7802/th3w.png
我做错了什么?记录类似于List。
目标:我想将Records
保存在Storage
中。我应该重写Storage
吗?
还附上Record class
:
public class Record {
private int number;
private int count;
private Object code;
public Record(int number, int count, Object code)
{
this.number = number;
this.count = count;
this.code = code;
}
错误:变量“storage”可能尚未初始化
如果我没有那个时刻的数据,我无法初始化这个变量。
答案 0 :(得分:3)
您的storage
变量刚刚声明但从未初始化,因此在使用时会出错。你应该至少使用:
Storage storage = new Storage();
由于您的Storage
需要创建Record
变量,因此更好的策略是
Storage storage = null;
try {
// ...
if (storage == null) {
storage = new Storage(new Record(j, Integer.parseInt(ContentCount), RowContent));
} else {
storage.addRecord(j, Integer.parseInt(ContentCount), RowContent));
}
} catch (...) {
// ...
}
正如您所看到的,此代码基于您当前的设计,导致问题而不是Storage
类的可读性和可用性。一些建议:
null
初始化(请注意,您传递Record
参数但是从不使用它= \)。List<Record> record
字段的名称更改为意味着它是List
的字段。我建议至少recordList
。Record
并发送此对象,而不是传递构造函数中所需的参数。遵循这些建议,您的代码应如下所示:
public class Storage {
List<Record> recordList;
public Storage() {
this.recordList = new ArrayList<Record>();
}
public void addRecord(Record record) {
recordList.add(record);
}
}
// previous code ...
Storage storage = new Storage();
try {
// ...
Record record = new Record(j, Integer.parseInt(ContentCount), RowContent));
storage.add(record);
} catch (...) {
// ...
}
提示:下次,不要显示当前代码的图片,而是显示实际代码的SSCCE。
答案 1 :(得分:1)
将storage
初始化为某个值。似乎
Storage storage = new Storage();
答案 2 :(得分:1)
你永远不会storage
此外,您的Storage构造函数似乎不正确。
Storage(Record newRecord){
this.record = new ArrayList<Record>();
}
您根本没有使用该参数。完全删除它(推荐)或使用它:
Storage(Record newRecord){
this.record = new ArrayList<Record>();
this.record.add(newRecord);
}
另外,我建议将Storage.record
字段名称更改为records
或recordCollection
。它更容易阅读和理解。