简体   繁体   English

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

[英]How can I get only specific values from an Arraylist

I have an ArrayList<Integer> with values (20, 40, 60, 80, 100, 120) Is it possible to only retrieve the position 2-5 only which is 60, 80, 100 and 120 ? 我有一个ArrayList<Integer> ,其值为(20, 40, 60, 80, 100, 120)是否可以仅检索位置2-5 ,即60, 80, 100 and 120 Thanks for any help. 谢谢你的帮助。

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));
}

In Java you can create a sublist ( javadoc ) of a list; 在Java中,您可以创建列表的子列表( javadoc ); eg 例如

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

Notes: 笔记:

  1. The the upper bound is exclusive, so that to get the list element containing 120 we must specify 6 as the upper bound, not 5 . 上限是独占的,因此要获得包含120的list元素,我们必须指定6作为上限,而不是5

  2. The resulting sublist is "backed" by the original list. 生成的子列表由原始列表“支持”。 Therefore: 因此:

    • there is no copying involved in creating the sublist, and 创建子列表时不涉及复制,并且
    • changes to the sublist will modify the corresponding positions in the original list. 对子列表的更改将修改原始列表中的相应位置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM