当前位置: 代码迷 >> java >> 如何才能从Arraylist中获取特定值
  详细解决方案

如何才能从Arraylist中获取特定值

热度:30   发布时间:2023-07-25 19:39:46.0

我有一个ArrayList<Integer> ,其值为(20, 40, 60, 80, 100, 120)是否可以仅检索位置2-5 ,即60, 80, 100 and 120 谢谢你的帮助。

for (DataSnapshot price : priceSnapshot.getChildren()) {
    int pr = price.getValue(Integer.class);
    priceList.add(pr); // size is 61 
}
int total = 0;
List<Integer> totalList = 
            new ArrayList<Integer>(priceList.subList(29, 34));               
for (int i = 0; i < totalList.size(); i++) {
    int to = totalList.get(i);
    total += to;
    txtPrice.setText(String.valueOf(total));
}

在Java中,您可以创建列表的子列表( ); 例如

List<Integer> list = ...
List<Integer> sublist = list.sublist(2, 6);

笔记:

  1. 上限是独占的,因此要获得包含120的list元素,我们必须指定6作为上限,而不是5

  2. 生成的子列表由原始列表“支持”。 因此:

    • 创建子列表时不涉及复制,并且
    • 对子列表的更改将修改原始列表中的相应位置。
  相关解决方案