Java ArrayList分页

今天遇到一个问题,需要把数据先取到内存中,再进行分页操作返回指定页码的数据。记录一下通过subList方法来返回数据:

import java.util.ArrayList;
import java.util.List;

/**
 * Create by zxb on 2017/5/10
 */
public class SubListTest {

    public static void main(String[] args) throws ClassNotFoundException {
        List list = new ArrayList<>();
        for (int i = 0; i < 22; i++) {
            list.add(i);
        }
        int pageNo = 2;   //从1开始
        int pageSize = 15;
        int fromIndex = pageSize * (pageNo - 1);
        int toIndex = pageSize * pageNo;
        if (toIndex > list.size()) {
            toIndex = list.size();
        }
        if (fromIndex > toIndex) {
            fromIndex = toIndex;
        }
        System.out.println(fromIndex+","+toIndex);  //15,22
        System.out.println(list.subList(fromIndex, toIndex));  //[15, 16, 17, 18, 19, 20, 21]
    }
}


你可能感兴趣的:(Java语言特性)