我正在从sharedPrefences在onCreate的arraylist中添加项目,但是在执行此操作之前我需要初始化我的arraylist吗?

private ArrayList<Song> songList = null;

//Initialize mSharedPreferences
storageUtil = new StorageUtil(this);

//Load values from mSharedPreferences
songList = storageUtil.getRecentPlayed();


还是这样做

private ArrayList<Song> songList = null;

songList = new ArrayList<>();

//Initialize mSharedPreferences
storageUtil = new StorageUtil(this);

//Load values from mSharedPreferences
songList = storageUtil.getRecentPlayed();


第一个工作正常,并在日志中显示我的物品。

最佳答案

否。songList变量值完全由songList = storageUtil.getRecentPlayed();代替。如果您首先将值扔进垃圾收集器,则不需要初始化。实际上,即使最初将其设置为null也无济于事。您的代码应为:

storageUtil = new StorageUtil(this);
private ArrayList<Song> songList = storageUtil.getRecentPlayed();

10-04 23:13