java修改数组长度/大小

来源:互联网 发布:数控铣床加工中心编程 编辑:程序博客网 时间:2024/06/05 05:28
 

java修改数组长度/大小

分类: Java
java中没有关于修改数组长度的api,在此本人提供了修改数组长度的两个函数:arrayAddLength()和arrayReduceLength().详细见代码. 

[java] view plaincopyprint?
  1. import java.lang.reflect.Array;  
  2.   
  3. /** 
  4. * Description: This class is used to adjust array length. 
  5. * @author e421083458 
  6. * 
  7. */  
  8. public class ArrayTest {  
  9.   
  10. /** 
  11. * @param args 
  12. */  
  13. public static void main(String[] args) {  
  14. int a[]= new int[]{0,1,2,3,4,5};  
  15. int b[]= new int[]{0,1,2,3,4,5};  
  16. a = (int[]) arrayAddLength(a,2);  
  17. b = (int[]) arrayReduceLength(b,2);  
  18. //out print array lenght  
  19. System.out.println(a.length);  
  20. for (int i=0;i<a.length;i++){  
  21. System.out.print(a[i]);  
  22. }  
  23. System.out.println();  
  24.   
  25. System.out.println(b.length);  
  26. for (int i=0;i<b.length;i++){  
  27. System.out.print(b[i]);  
  28. }  
  29. }  
  30. /** 
  31. * Description: Array add length 
  32. * @param oldArray 
  33. * @param addLength 
  34. * @return Object 
  35. */  
  36. public static Object arrayAddLength(Object oldArray,int addLength) {  
  37. Class c = oldArray.getClass();  
  38. if(!c.isArray())return null;  
  39. Class componentType = c.getComponentType();  
  40. int length = Array.getLength(oldArray);  
  41. int newLength = length + addLength;  
  42. Object newArray = Array.newInstance(componentType,newLength);  
  43. System.arraycopy(oldArray,0,newArray,0,length);  
  44. return newArray;  
  45. }  
  46. /** 
  47. * Description: Array reduce lenght 
  48. * @param oldArray 
  49. * @param reduceLength 
  50. * @return Object 
  51. */  
  52. public static Object arrayReduceLength(Object oldArray,int reduceLength) {  
  53. Class c = oldArray.getClass();  
  54. if(!c.isArray())return null;  
  55. Class componentType = c.getComponentType();  
  56. int length = Array.getLength(oldArray);  
  57. int newLength = length - reduceLength;  
  58. Object newArray = Array.newInstance(componentType,newLength);  
  59. System.arraycopy(oldArray,0,newArray,0,newLength);  
  60. return newArray;  
  61. }  
  62. }  
0 0
原创粉丝点击