V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
sharkv
V2EX  ›  问与答

请教大家关于 JDK 的 Arrays 类的 copyOf 方法

  •  1
     
  •   sharkv · 2018-08-03 21:13:18 +08:00 · 915 次点击
    这是一个创建于 2065 天前的主题,其中的信息可能已经有所发展或是发生改变。

    想问下 jdk 的 Arrays 工具类的 copyof 方法,不能保证把 original 的元素“扔到”新数组中去啊。 为什么不限定 T 和 U 的关系呢?比如 public static <T,U extends T> T[] copyOf(U[] original, int newLength, Class<T[]> newType)。

    public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
            @SuppressWarnings("unchecked")
            T[] copy = ((Object)newType == (Object)Object[].class)
                ? (T[]) new Object[newLength]
                : (T[]) Array.newInstance(newType.getComponentType(), newLength);
            System.arraycopy(original, 0, copy, 0,
                             Math.min(original.length, newLength));
            return copy;
    }
    
    想听听大佬们的看法。
    
    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2831 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 14:54 · PVG 22:54 · LAX 07:54 · JFK 10:54
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.