public class Pagination {
private int total; // 总记录数
private int size; // 每页记录数
private int currentPage; // 当前页码
private int totalPages; // 总页数
public Pagination(int total, int size) {
this.total = total;
this.size = size;
this.currentPage = 1; // 默认当前页码为1
calculateTotalPages();
}
// 计算总页数
private void calculateTotalPages() {
this.totalPages = (int) Math.ceil((double) total / size);
}
// 获取当前页码
public int getCurrentPage() {
return currentPage;
}
// 设置当前页码
public void setCurrentPage(int currentPage) {
if (currentPage < 1) {
this.currentPage = 1;
} else if (currentPage > totalPages) {
this.currentPage = totalPages;
} else {
this.currentPage = currentPage;
}
}
// 获取每页记录数
public int getSize() {
return size;
}
// 获取总页数
public int getTotalPages() {
return totalPages;
}
// 获取总记录数
public int getTotal() {
return total;
}
// 计算当前页的起始记录索引
public int getStartIndex() {
return (currentPage - 1) * size;
}
// 以下为示例方法,展示如何使用分页类
public static void main(String[] args) {
// 假设我们有100条记录,每页显示10条
Pagination pagination = new Pagination(100, 10);
// 打印分页信息
System.out.println("总页数: " + pagination.getTotalPages());
System.out.println("每页记录数: " + pagination.getSize());
System.out.println("当前页码: " + pagination.getCurrentPage());
System.out.println("当前页起始记录索引: " + pagination.getStartIndex());
// 设置当前页为第5页
pagination.setCurrentPage(5);
System.out.println("当前页码: " + pagination.getCurrentPage());
System.out.println("当前页起始记录索引: " + pagination.getStartIndex());
}
}