当前位置: 移动技术网 > IT编程>开发语言>Java > Java中动态地改变数组长度及数组转Map的代码实例分享

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

2019年07月22日  | 移动技术网IT编程  | 我要评论
动态改变数组的长度 /** * 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"));    
}   
} 

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网