How to implement pagination functionality using Java code?
Here is an example of implementing pagination functionality using Java code.
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);
}
}
When using, you can pass the total number of records, current page number, and number of records displayed per page to the constructor, then use the getTotalPages method to get the total number of pages, and use the getStartIndex and getEndIndex methods to get the starting index and ending index of the records displayed on the current page.
Example usage:
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);
}
}
Result of the operation:
总页数:4
起始索引:10
结束索引:20
In this example, there are a total of 37 records, with 10 records displayed per page. The current page is the second page. Therefore, the total number of pages is 4, with the starting index of the current page being 10 and the ending index being 20.