V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
Weixiao0725
V2EX  ›  Java

Arrays.copyOf(U[] original, int newLength, Class<? extends T[]> newType)方法答疑

  •  
  •   Weixiao0725 · 2018-02-28 23:31:03 +08:00 · 2413 次点击
    这是一个创建于 2219 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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;
        }
    

    这段代码中为什么会有 ((Object)newType == (Object)Object[].class) 的判断,难道直接 (T[]) Array.newInstance(newType.getComponentType(), newLength); 不能处理前面那种情况吗?我单独把这个函数拿出来,去掉三元表达式前面的判断,然后调用 copyOf(intArr, 5, Object[].class) 试了一下,貌似也可以啊。

    3 条回复    2018-02-28 23:42:21 +08:00
    aristotll
        1
    aristotll  
       2018-02-28 23:40:32 +08:00
    应该是效率问题吧 反射慢吧
    1stlulu
        2
    1stlulu  
       2018-02-28 23:40:35 +08:00 via Android   ❤️ 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3169 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 12:34 · PVG 20:34 · LAX 05:34 · JFK 08:34
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.