簡體   English   中英

如何才能從Arraylist中獲取特定值

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

我有一個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中,您可以創建列表的子列表( javadoc ); 例如

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

筆記:

  1. 上限是獨占的,因此要獲得包含120的list元素,我們必須指定6作為上限,而不是5

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

    • 創建子列表時不涉及復制,並且
    • 對子列表的更改將修改原始列表中的相應位置。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM