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

Java中动态地改变数组长度及数组转Map的代码实例分享

程序员文章站 2024-03-09 18:06:29
动态改变数组的长度 /** * reallocates an array with a new size, and copies the contents...

动态改变数组的长度

/** * 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"));    
}   
}