Array,List分页代码

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();

	}

}

 

你可能感兴趣的:(array)