如何检查 ArrayList 是否为空

3
我试图检查我的已保存ArrayList是否为空。当我运行这段代码时:
  protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

        Intent intent = this.getIntent();
        String title = intent.getStringExtra(NotePad.EXTRA_MESSAGE);
        notes.add(title);
        Log.d("testt", "notes: " + notes);

        if(title != null) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            SharedPreferences.Editor editor = prefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(notes);
            editor.putString(Key, json);
            editor.apply();
            Log.d("ans", "notes: " + notes);
        }

        int t = CheckSharedPreferences();
        Log.d("testt","t: "+t);
}

int CheckSharedPreferences() {
    ArrayList<String> test = new ArrayList<String>();

    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
    Gson gson = new Gson();
    String json = prefs.getString(Key, null);
    Type type = new TypeToken<ArrayList<String>>() {}.getType();
    test = gson.fromJson(json, type);

    Log.d("testt", "test " + test);

    if(test == null) {
        return 1;
    } else {
        return 0;
    }
}

即使列表为空,该方法始终返回0

这是日志中的一小段:

10-10 01:12:38.254 19365-19365/com.example.quicknote D/testt: notes: [null]
10-10 01:12:38.281 19365-19365/com.example.quicknote D/testt: test[null]
10-10 01:12:38.281 19365-19365/com.example.quicknote D/testt: t: 0

“is empty”是什么意思?如果你有String s = null,那么s变量不持有空字符串,而是引用了null。要持有空字符串,你需要写类似于String s = "";的代码,因为这样的字符串存在但不包含任何字符,所以可以被认为是空的。同样,在你的情况下,if(test == null)并不检查test是否持有空列表,而是检查它是否持有null而不是任何列表。你想要的可能是if(test.isEmpty()) - Pshemo
我想检查是否为空。 - shaswat kumar
4个回答

3

检查您的日志,似乎

test = gson.fromJson(json, type);

返回一个包含 null 作为第一个/唯一元素的列表。

在 if 内部,你必须检查以下三个条件:

if ( test == null || test.isEmpty() || test.get(0) == null ) { return 1;}

但为什么要检查所有三个条件。test == null 和 test.get(0) == null 不是一回事吗? - shaswat kumar
test == null 表示变量引用了 null,但 test.get(0) == null 表示检查列表的第一个元素是否引用了 null,因此两者是不同的情况。 - Bilal Siddiqui

1
尝试使用 test.isEmpty() 而不是 test == null

0

test 永远不会是 null,因为你在这个变量之前已经分配了一个对象:ArrayList<String> test = new ArrayList<String>();

尝试使用这个代替:if(test.isEmpty())


0

或者,您也可以通过 .size() 方法进行检查。那些不为空的列表将具有大于零的大小

if (test.size()>0){
//execute your code
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接