zoukankan      html  css  js  c++  java
  • 通过反射修改已有数组的大小

    import java.lang.reflect.Array;

    public class ChangeArrayDemo {
        public static void main(String[] args) {
            int temp[] = { 1, 2, 3 };
            int newTemp[] = (int[]) arrayInc(temp, 5);
            print(newTemp);
            System.out.println(" =============================");
            String t[] = { "von", "mldn", "java" };
            String nt[] = (String[]) arrayInc(t, 8);
            print(nt);
        }

        public static Object arrayInc(Object obj, int len) {
            Class<?> c = obj.getClass();
            Class<?> arr = c.getComponentType();
            Object newO = Array.newInstance(arr, len);
            int co = Array.getLength(obj);
            System.arraycopy(obj, 0, newO, 0, co);
            return newO;
        }

        public static void print(Object obj) {
            Class<?> c = obj.getClass();
            if (!c.isArray()) {
                return;
            }
            Class<?> arr = c.getComponentType();
            System.out.println(arr.getName() + "Array's length is:"
                    + Array.getLength(obj));
            for (int i = 0; i < Array.getLength(obj); i++) {
                System.out.print(Array.get(obj, i) + ",");
            }
        }
    }

  • 相关阅读:
    09 python初学 (字符串)
    08 python 初学(字典)
    07 Python初学(元组)
    ubuntu 学习
    10 python 初学(Python 的编码解码)
    12 python 初学(深浅拷贝、集合)
    11 python初学 (文件)
    ubuntu 在 Windows 下的安装
    mysql常用命令总结
    关于Windows 7 下临时IPV6地址的问题,如何禁用它
  • 原文地址:https://www.cnblogs.com/vonk/p/3956650.html
Copyright © 2011-2022 走看看