Bitmap Bitmap - 4 months ago 10
Java Question

Paginating an ArrayList

I am trying to create a simple pagination routine for values held in an

ArrayList
. Basically what I want to do is render the first five elements in the
ArrayList
at first go. And then when users click on
Next (increment by another 5)
and
Previous (decrease by 5)
.

My logic looks like this:

class foo
{
private static final int defaultStep = 5;
private int moveCounter;
private List<String> values;

public foo()
{
values = new ArrayList<String>();
values.add("Fiber Channel");
values.add("Copper Channel");
...
}

private void pageNext()
{
if (moveCounter > -1 && moveCounter < values.size())
{
int currentIndex = (moveCounter + 1);
renderValues(currentIndex, false);
}
}

private void pagePrevious()
{
if (moveCounter > -1 && moveCounter <= values.size())
{
renderValues(moveCounter-1, true);
}
}

private void renderValues(int startIndex, boolean isPreviousCall)
{
if (startIndex > -1)
{
StringBuilder html = new StringBuilder();
List<String> valuesToRender = new ArrayList<String>();
int checkSteps = 1;
while (startIndex < values.size())
{
valuesToRender.add(values.get(startIndex));
if (checkSteps == defaultStep) break;
startIndex++;
checkSteps++;
}
moveCounter = startIndex;

//TODO: Build html String
...
}
}
}


I have an issue with
pagePrevious
call, can you guys help me build the
valuesToRender
5-steps up
values array
before adding the value to render to the
valuesToRender
array.

I tried doing something like this also:

for (int start = startIndex, end = values.size() - 1; start < end; start++, end--)
{
if (isPreviousCall) valuesToRender.add(values.get(end));
else valuesToRender.add(values.get(start));

if (checkSteps == defaultStep) break;
checkSteps++;
}


But this doesn't seems to work neither. Can you guys spot and help me fix this issue.
Thanks Guys.

Answer

I would do it like this:

I'm not sure what renderValues does, and whether we have to substract 1 or maybe defaultStep from the upper bound of the moveCounter.

private void pageMove (int step)
{
    moveCounter = moveCounter + step;
    if (moveCounter < 0) moveCounter = 0;
    if (moveCounter > values.size ()) moveCounter = values.size ();
    renderValues (currentIndex, false);
}

private void pageNext ()
{
    pageMove (defaultStep);
}

private void pagePrevious ()
{
    pageMove (-defaultStep);
}

The first 3 lines could be packed into two big ternary experssions like so:

mc = ((mc + s) < 0) ? 0 : ((mc + s) > vs) ? vs : (mc + s); 

but the 3 lines solution is better to follow.