Weixiao0725
V2EX  ›  Java

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

  •  
  •   Weixiao0725 · Feb 28, 2018 · 3129 views
    This topic created in 3004 days ago, the information mentioned may be changed or developed.
    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 replies    2018-02-28 23:42:21 +08:00
    aristotll
        1
    aristotll  
       Feb 28, 2018
    应该是效率问题吧 反射慢吧
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1094 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 79ms · UTC 18:18 · PVG 02:18 · LAX 11:18 · JFK 14:18
    ♥ Do have faith in what you're doing.