首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何才能从Arraylist中获得特定的值?

如何才能从Arraylist中获得特定的值?
EN

Stack Overflow用户
提问于 2019-03-03 07:23:28
回答 1查看 453关注 0票数 3

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

代码语言:javascript
复制
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));
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-03 07:50:44

在Java中,您可以创建一个列表的子列表(javadoc)。

代码语言:javascript
复制
List<Integer> list = ...
List<Integer> sublist = list.sublist(2, 6);

备注:

  1. 上限是排他性的,因此要获得包含120的list元素,我们必须指定6作为上限,而不是5
  2. 生成的子列表由原始列表“支持”。因此:
代码语言:javascript
复制
- there is no copying involved in creating the sublist, and
- changes to the sublist will modify the corresponding positions in the original list.

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54966526

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档