问题描述
我有一个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));
}
1楼
在Java中,您可以创建列表的子列表( ); 例如
List<Integer> list = ...
List<Integer> sublist = list.sublist(2, 6);
笔记:
上限是独占的,因此要获得包含
120
的list元素,我们必须指定6
作为上限,而不是5
。生成的子列表由原始列表“支持”。 因此:
- 创建子列表时不涉及复制,并且
- 对子列表的更改将修改原始列表中的相应位置。