Array,Listページングコード
3216 ワード
package com.snail.util;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author penghuaiyi
* @date 2013-08-30
*/
public class PageUtils {
/**
*
* @param source
* @param pageSize
* @return
*/
public static <T> List<T[]> pageArray(T[] source, int pageSize){
int totalLength = source.length; //
int totalPage = totalLength%pageSize==0 ? totalLength/pageSize : totalLength/pageSize+1; //
List<T[]> list = new ArrayList<T[]>(totalPage);
for(int page=1; page<=totalPage; page++){
int startIndex = (page-1)*pageSize;
int endIndex = startIndex+pageSize-1;
if(endIndex>=totalLength){
endIndex = totalLength-1;
}
int len = endIndex-startIndex+1;
T[] pageData = (T[]) Array.newInstance(source.getClass().getComponentType(), len);
System.arraycopy(source, startIndex, pageData, 0, len);
list.add(pageData);
}
return list;
}
/**
* List
* @param source list
* @param pageSize
* @return
*/
public static <T> List<List<T>> pageList(List<T> source, int pageSize){
int totalLength = source.size(); //
int totalPage = totalLength%pageSize==0 ? totalLength/pageSize : totalLength/pageSize+1; //
List<List<T>> list = new ArrayList<List<T>>(totalPage);
for(int page=1; page<=totalPage; page++){
int startIndex = (page-1)*pageSize;
int endIndex = startIndex+pageSize-1;
if(endIndex>=totalLength){
endIndex = totalLength-1;
}
List<T> pageData = source.subList(startIndex, endIndex+1);
list.add(pageData);
}
return list;
}
public static void testPageArray(){
Integer[] source = new Integer[100];
for(int i=0;i<100;i++){
source[i] = i;
}
List<Integer[]> rtn = pageArray(source,15);
for(Integer[] value : rtn){
for(Integer in : value){
System.out.print(in+" ");
}
System.out.println();
}
}
public static void testPageList(){
List<Integer> source = new ArrayList<Integer>(100);
for(int i=0;i<100;i++){
source.add(i);
}
List<List<Integer>> rtn = pageList(source,15);
for(List<Integer> value : rtn){
for(Integer in : value){
System.out.print(in+" ");
}
System.out.println();
}
}
/**
* @param args
*/
public static void main(String[] args) {
testPageArray();
System.out.println("*******************");
testPageList();
}
}