简体   繁体   中英

Loop in arraylist

This is my 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.

Then automatically next 5 result likewise.

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.

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,

You can use ArrayList.removeRange(int fromIndex, int toIndex) every time you press that button (But don't iterate this )

or easily use 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. Shifts any succeeding elements to the left (reduces their index). This call shortens the list by (toIndex - fromIndex) elements. (If toIndex==fromIndex, this operation has no effect.)

Read document > 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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