zoukankan      html  css  js  c++  java
  • 利用反射扩展数组长度

    利用反射扩展数组长度

    思想:要扩展数组长度其实就是产生一个新的数组覆盖旧的数组

    import java.lang.reflect.*;
    
    public class Answer {
    
        public static void main(String[] args) {
    
            Test test = new Test();
    
            test.print(); //打印数组的内容
    
            test.is = (int[]) addArrayLength(test.is, 10);  //用新的数组覆盖旧的数组
            test.ss = (String[]) addArrayLength(test.ss, 10);  
    
            test.print();
    
        }
    
        public static Object addArrayLength(Object array, int newLength) {
            Object newArray = null;
            Class componentType = array.getClass().getComponentType();  //得到一个数组的class对象
            newArray = Array.newInstance(componentType, newLength);     //动态创建数组
            System.arraycopy(array, 0, newArray, 0, Array.getLength(array));  //数组之间的复制
            return newArray;
        }
    }
    
    class Test {
    
        public int[] is = { 1, 2, 3 };
    
        public String[] ss = { "A", "B", "C" };
    
        public void print() {
    
            for (int index = 0; index < is.length; index++) {
                System.out.println("is[" + index + "]=" + is[index]);
            }
    
            System.out.println();
    
            for (int index = 0; index < ss.length; index++) {
                System.out.println("ss[" + index + "]=" + ss[index]);
            }
    
            System.out.println();
    
        }
    
    }

    备注:

    array.getClass().getComponentType() 得到一个数组的class对象
    Array.newInstance(componentType, newLength)  动态创建指定类型的数组
    System.arraycopy(array, 0, newArray, 0, Array.getLength(array)) 实现数组之间的复制,这五个参数分别代表被复制的数组,起始位置,复制到的数组,起始位置,长度
    务实,说实话!
  • 相关阅读:
    一个程序员的职业规划
    基于Andoird 4.2.2的Account Manager源代码分析学习:创建选定类型的系统帐号
    [置顶] C++学习书单
    js快速分享代码
    The declared package does not match the expected package
    IBM Rational Appscan Part 1
    IBM Rational Appscan: Part 2 ---reference
    阅读redis源代码的一些体会
    18 Command Line Tools to Monitor Linux Performance
    代码规范
  • 原文地址:https://www.cnblogs.com/xtuxiongda/p/8586361.html
Copyright © 2011-2022 走看看