程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> JAVA編程 >> 關於JAVA >> Java中靜態地轉變數組長度及數組轉Map的代碼實例分享

Java中靜態地轉變數組長度及數組轉Map的代碼實例分享

編輯:關於JAVA

Java中靜態地轉變數組長度及數組轉Map的代碼實例分享。本站提示廣大學習愛好者:(Java中靜態地轉變數組長度及數組轉Map的代碼實例分享)文章只能為提供參考,不一定能成為您想要的結果。以下是Java中靜態地轉變數組長度及數組轉Map的代碼實例分享正文


靜態轉變數組的長度

/** * Reallocates an array with a new size, and copies the contents  
 * * of the old array to the new array.  
 * * @param oldArray the old array, to be reallocated.  
 * * @param newSize  the new array size.  
 * * @return     A new array with the same contents.  
 * */  
private static Object resizeArray (Object oldArray, int newSize) {    
  int oldSize = java.lang.reflect.Array.getLength(oldArray);    
  Class elementType = oldArray.getClass().getComponentType();    
  Object newArray = java.lang.reflect.Array.newInstance(       
      elementType,newSize);    
  int preserveLength = Math.min(oldSize,newSize);    
  if (preserveLength > 0)      
    System.arraycopy (oldArray,0,newArray,0,preserveLength);    
  return newArray;  }    
// Test routine for resizeArray().   
public static void main (String[] args) {    
  int[] a = {1,2,3};    
  a = (int[])resizeArray(a,5);    
  a[3] = 4;    
  a[4] = 5;    
  for (int i=0; i<a.length; i++)      
    System.out.println (a[i]);   
} 

代碼只是完成基本辦法,具體處置還須要你去Coding哦>>

把 Array 轉換成 Map

import java.util.Map;   
import org.apache.commons.lang.ArrayUtils;    
public class Main {     
  public static void main(String[] args) {     
    String[][] countries = { { "United States", "New York" },  
        { "United Kingdom", "London" },       
        { "Netherland", "Amsterdam" },  
        { "Japan", "Tokyo" },  
        { "France", "Paris" } };      
    Map countryCapitals = ArrayUtils.toMap(countries);      
    System.out.println("Capital of Japan is " + countryCapitals.get("Japan"));     
    System.out.println("Capital of France is " + countryCapitals.get("France"));    
}   
} 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved