简体   繁体   English

在数组列表中循环

[英]Loop in arraylist

This is my ArrayList :这是我的ArrayList

{10, 20, 30,40, 50, 60, 70, 80, 90, 100....1000}

I want to loop my result on button click.我想在单击按钮时循环我的结果。

I want first 5 results in first Button 's click.我想要第一个Button的点击中的前 5 个结果。

Then automatically next 5 result likewise.然后同样自动下5个结果。

Is there any way I can do that?有什么办法可以做到吗?

for(int i=0 ;i<5; i++) {
   list = array.getJSONObject(i);
   fr.add(list.get("contact"));
 }

The problem is that I am only getting first 5 not next results.问题是我只得到前 5 个而不是下一个结果。

Thanks for helping.谢谢你的帮助。

If you want to remove first N items in an array list every time you call a method from index a to index b,如果您想在每次从索引 a 到索引 b 调用方法时删除数组列表中的前 N ​​个项目,

You can use ArrayList.removeRange(int fromIndex, int toIndex) every time you press that button (But don't iterate this )每次按下该按钮时ArrayList.removeRange(int fromIndex, int toIndex)您都可以使用ArrayList.removeRange(int fromIndex, int toIndex) (但不要重复此操作)

or easily use ArrayList.subList(start, end).clear();或轻松使用ArrayList.subList(start, end).clear(); for the same task!为同样的任务!

Removes from this list all of the elements whose index is between fromIndex, inclusive, and toIndex, exclusive.从此列表中删除其索引介于 fromIndex(包含)和 toIndex(不包含)之间的所有元素。 Shifts any succeeding elements to the left (reduces their index).将任何后续元素向左移动(减少它们的索引)。 This call shortens the list by (toIndex - fromIndex) elements.此调用通过 (toIndex - fromIndex) 元素缩短列表。 (If toIndex==fromIndex, this operation has no effect.) (如果 toIndex==fromIndex,则此操作无效。)

Read document > http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#removeRange%28int,%20int%29阅读文档 > http://docs.oracle.com/javase/6/docs/api/java/util/ArrayList.html#removeRange%28int,%20int%29

example :例子 :

public void removeFistNItemsFromList(){

    for(int i=0 ;i<n; i++) {
     // add your items or do what ever you want!
    }
    myArray.subList(0, 4).clear(); // here from 0 to 4th index items will be removed and  list will be updated!
    System.out.println("MyArrayListNow:"+myArray);
}

output after each click :每次点击后输出:

在此处输入图片说明

Well, you are trying to reading first 5 elements always hence the problem.好吧,你总是试图阅读前 5 个元素,因此问题。 One option you have read and remove the elements from the arraylist.您已阅读并从数组列表中删除元素的一种选择。 But a better approach would be to keep a count of mouse click, in which case it is a classic pagination problem, and u can fetch the next 5 elements and you will not lose the data in arraylist.但是更好的方法是记录鼠标点击次数,在这种情况下,这是一个经典的分页问题,​​您可以获取接下来的 5 个元素,并且不会丢失 arraylist 中的数据。

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

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