怎么用java代码实现分页功能

   2025-02-13 7920
核心提示:以下是一个用Java代码实现分页功能的示例:public class Pagination {private int currentPage;private int pageSize;private in

以下是一个用Java代码实现分页功能的示例:

public class Pagination {    private int currentPage;    private int pageSize;    private int totalRecords;    public Pagination(int currentPage, int pageSize, int totalRecords) {        this.currentPage = currentPage;        this.pageSize = pageSize;        this.totalRecords = totalRecords;    }    public int getTotalPages() {        return (int) Math.ceil((double) totalRecords / pageSize);    }    public int getStartIndex() {        return (currentPage - 1) * pageSize;    }    public int getEndIndex() {        return Math.min(currentPage * pageSize, totalRecords);    }}

在使用时,可以将总记录数、当前页数和每页显示的记录数传递给构造函数,然后使用getTotalPages方法获取总页数,使用getStartIndexgetEndIndex方法获取当前页显示的记录的起始索引和结束索引。

示例用法:

public class Main {    public static void main(String[] args) {        int currentPage = 2;        int pageSize = 10;        int totalRecords = 37;        Pagination pagination = new Pagination(currentPage, pageSize, totalRecords);        int totalPages = pagination.getTotalPages();        int startIndex = pagination.getStartIndex();        int endIndex = pagination.getEndIndex();        System.out.println("总页数:" + totalPages);        System.out.println("起始索引:" + startIndex);        System.out.println("结束索引:" + endIndex);    }}

运行结果:

总页数:4起始索引:10结束索引:20

这个示例中,总记录数为37,每页显示10条记录,当前页为第2页。所以总页数为4,当前页的起始索引为10,结束索引为20。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言