分页工具类

阅读更多
package com.movie.cartoon.web.admin.bean;

/**
 * Created on 2016/12/26.
 */
import java.util.ArrayList;
import java.util.List;

/** 分页类:根据总记录数和分页大小对 {@link List} 进行分页处理 */
public class Page
{
    public static final int DEFAULT_PAGE_SIZE = 10;

    private int rowCount;//总记录数
    private int currentPage;//当前页码
    private int pageSize;//每页显示条数
    private int pageCount;//总页数

    private List list;

    public Page(List list)
    {
        this(list, DEFAULT_PAGE_SIZE);
    }

    public Page(List list, int pageSize)
    {
        this.currentPage    = 1;
        this.list            = list;
        this.rowCount        = list.size();

        setPageSize(pageSize);
    }

    private void adjustPageCount()
    {
        pageCount = (rowCount + pageSize - 1) / pageSize;
    }

    /** 获取要分页的 {@link List}  */
    public List getList()
    {
        return list;
    }

    /** 获取的 {@link List} 当前页内容 */
    public List getCurrentList()
    {
        List currentList = null;

        if(currentPage >= 1 && currentPage <= pageCount)
        {
            int index = (currentPage - 1) * pageSize;
            currentList = list.subList(index, (currentPage < pageCount) ? (index + pageSize) : rowCount);
        }

        return currentList;
    }


    /** 获取当前页号(从 1 开始) */
    public int getCurrentPage()
    {
        return currentPage;
    }

    /** 设置当前页号(从 1 开始) */
    public boolean setCurrentPage(int page)
    {
        if(page >= 1 && page <= pageCount)
        {
            currentPage = page;
            return true;
        }

        return false;
    }

    /** 转到下一页 */
    public boolean nextPage()
    {
        return setCurrentPage(currentPage + 1);
    }

    /** 转到上一页 */
    public boolean prePage()
    {
        return setCurrentPage(currentPage - 1);
    }

    /** 获取分页大小 */
    public int getPageSize()
    {
        return pageSize;
    }

    /** 设置分页大小 */
    public void setPageSize(int size)
    {
        if(size <= 0)
            size = DEFAULT_PAGE_SIZE;

        int index = (currentPage - 1) * pageSize;

        pageSize = size;

        if(index > pageSize)
            currentPage = (index + pageSize - 1) / pageSize;
        else
            currentPage = 1;

        adjustPageCount();
    }

    /** 获取总页数 */
    public int getPageCount()
    {
        return pageCount;
    }


    public static void main(String[] args)
    {
        final int PAGE_SIZE        = 10;
        final int LIST_SIZE        = 39;

        List list = new ArrayList<>();
        for(int i = 1; i <= LIST_SIZE; i++){
            list.add(i);
        }

        Page pg = new Page(list, PAGE_SIZE);

        for(int i = 1; i <= pg.getPageCount(); i++)
        {
            pg.setCurrentPage(i);
            System.out.println(pg.getCurrentList());
        }
    }

}

你可能感兴趣的:(java分页工具类)