Created
August 22, 2022 09:30
-
-
Save Koboo/ec8024dbb1c2d10bcce860d5814da4ee to your computer and use it in GitHub Desktop.
Pagifier for generic Objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Pagifier<T> { | |
private final int maxItemsPerPage; | |
private final List<List<T>> allPages; | |
public Pagifier(int maxItemsPerPage) { | |
this.maxItemsPerPage = maxItemsPerPage; | |
allPages = new LinkedList<>(); | |
allPages.add(new LinkedList<>()); | |
} | |
public int getMaxItemsPerPage() { | |
return maxItemsPerPage; | |
} | |
public List<List<T>> getAllPages() { | |
return allPages; | |
} | |
public void addItem(T item) { | |
int pageNum = allPages.size() - 1; | |
List<T> currentPage = allPages.get(pageNum); | |
// Add new page if full | |
if (currentPage.size() >= maxItemsPerPage) { | |
currentPage = new LinkedList<>(); | |
allPages.add(currentPage); | |
} | |
currentPage.add(item); | |
} | |
public List<T> getPage(int pageNum) { | |
if (allPages.size() == 0) { | |
return null; | |
} | |
pageNum -= 1; | |
if (pageNum < 0) { | |
return null; | |
} | |
if (pageNum > (allPages.size() - 1)) { | |
return null; | |
} | |
return this.allPages.get(pageNum); | |
} | |
public void reset() { | |
for (List<T> page : allPages) { | |
page.clear(); | |
} | |
allPages.clear(); | |
allPages.add(new LinkedList<>()); | |
} | |
public int getTotalPageItems() { | |
int total = 0; | |
for (List<T> page : allPages) { | |
total += page.size(); | |
} | |
return total; | |
} | |
public int getTotalPages() { | |
return allPages.size(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment