sharkv
V2EX  ›  问与答

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

  •  1
     
  •   sharkv · Aug 3, 2018 · 1714 views
    This topic created in 2848 days ago, the information mentioned may be changed or developed.

    想问下 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;
    }
    
    想听听大佬们的看法。
    
    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2540 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 16:00 · PVG 00:00 · LAX 09:00 · JFK 12:00
    ♥ Do have faith in what you're doing.