如何从ArrayList通过键获取值?

时间:2018-09-09 19:41:42

标签: java android

我正在尝试使用arraylist.get(2);通过键来获取特定的索引值,但是失败了,而且还会引发异常。

  

“ IndexOutOfBoundsException:无效的索引2,大小为1”

我的阵列列表的大小为3(0-2)。

下面是我的方法代码:

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {

    //add keys to arraylist
    String key=dataSnapshot.getKey();
    arraylist.add(key);

    //it displays found indexes as 0, 1, 2
    int index= arraylist.indexOf(key);
    Log.i("indexs", String.valueOf(index));

    //it displays exception, but when I replace "2" with "0" then, 
    //it prints one value four times which lie on index "1"
    String specificIndexValue = arraylist.get(2);
    Log.i("IndexValues", specificIndexValue);

}

1 个答案:

答案 0 :(得分:1)

第一次调用onChildAdded时会出现一个异常,因为arraylist仅包含1个项目,并且您正在访问索引2,而该列表中需要3个或更多项目。

String specificIndexValue = arraylist.get(2);

我们将需要更多信息来解决您的问题it prints one value four times which lie on index "1"

似乎您可能希望将其存储在有序映射中而不是数组中,该键是快照键,而值是快照。

尝试此调试...

@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {

    //add keys to arraylist
    String key=dataSnapshot.getKey();
    arraylist.add(key);

    if (arraylist.size() == 3){
       Log.i("Key: " arraylist.get(2), "Index: 2");
    }
}
相关问题