`

数组拆分

    博客分类:
  • java
 
阅读更多


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;  
         } 
     

}






分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics