欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组拆分

程序员文章站 2022-05-28 17:00:40
...


import java.util.ArrayList;
import java.util.List;


public class TestArray {

	public static void main(String[] args) {
		
		 String[] ary = new String[]{"0","1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"};//要分割的数组  
         int splitSize = 5;//分割的块大小  
         Object[] subAry = splitAry(ary, splitSize);//分割后的子块数组  
            
         for(Object obj: subAry){//打印输出结果  
        	 String[] aryItem = (String[]) obj;  
              for(int i = 0; i < aryItem.length; i++){  
                  System.out.print(aryItem[i] + ", ");  
              }  
              System.out.println();  
         }  
 
         
	}
	
	
	/** 
     * splitAry方法<br> 
     * @param ary 要分割的数组 
     * @param subSize 分割的块大小 
     * @return 
     * 
     */  
    private static Object[] splitAry(String[] ary, int subSize) {  
          int count = ary.length % subSize == 0 ? ary.length / subSize: ary.length / subSize + 1;  
  
          List<List<String>> subAryList = new ArrayList<List<String>>();  
  
          for (int i = 0; i < count; i++) {  
           int index = i * subSize;  
           List<String> list = new ArrayList<String>();  
           int j = 0;  
               while (j < subSize && index < ary.length) {  
                    list.add(ary[index++]);  
                    j++;  
               }  
           subAryList.add(list);  
          }  
            
          Object[] subAry = new Object[subAryList.size()];  
            
          for(int i = 0; i < subAryList.size(); i++){  
               List<String> subList = subAryList.get(i);  
               String[] subAryItem = new String[subList.size()];  
               for(int j = 0; j < subList.size(); j++){  
                   subAryItem[j] = subList.get(j);  
               }  
               subAry[i] = subAryItem;  
          }  
            
          return subAry;  
         } 
     

}