简体   繁体   English

泛型-原始类型警告的正确处理:

[英]Generics - Correct treatment for raw type warnings:

When implementing a generic method, I used the following statement: 在实现通用方法时,我使用以下语句:

@SuppressWarning({"unchecked"})
private static <T extends Comparable<T>> T[] merge(T[] arrayA, T[] arrayB) {
  ...
  T[] result;

// This is the line that needs that gives warnings    
  result = (T[]) Array.newInstance(arrayA.getClass().getComponentType(), arrayA.length + arrayB.length);
  ...

Now, many programming sources state that it's good programming practice to avoid using @SuppressWarnings for unchecked raw types. 现在,许多编程资源都指出,避免对未经检查的原始类型使用@SuppressWarnings是一种良好的编程习惯。 In this case, however, I don't know how to address this warning in the code. 但是,在这种情况下,我不知道如何在代码中解决此警告。 Searching the net for best practice to instantiate generic types in Java doesn't give one clear approach. 在网上搜索最佳实践以实例化Java中的泛型类型并没有给出一种明确的方法。 In fact, many of the solutions I found are less than ideal. 实际上,我发现的许多解决方案都不理想。

In this piece of code, what would be the best approach to remove the raw type warning without adding the @SuppressWarnings to the method? 在这段代码中,在不向方法中添加@SuppressWarnings的情况下删除原始类型警告的最佳方法是什么? Is what I did the best approach? 我是最好的方法吗?

In some cases you can't avoid @SuppressWarnings . 在某些情况下,您无法避免@SuppressWarnings Even standard JDK classes use @SuppressWarnings("unchecked") when dealing with generic arrays. 处理通用数组时,甚至标准的JDK类都使用@SuppressWarnings("unchecked")

Example: 例:

Arrays class: Arrays类:

@SuppressWarnings("unchecked")
public static <T> T[] copyOf(T[] original, int newLength) {
    return (T[]) copyOf(original, newLength, original.getClass());
}

Speaking of Arrays.copyOf , you can use that method combined with System.arraycopy instead of your current logic: 说到Arrays.copyOf ,您可以将该方法与System.arraycopy结合使用,而不是使用当前的逻辑:

private static <T extends Comparable<T>> T[] merge(T[] arrayA, T[] arrayB) {
    T[] result = Arrays.copyOf (arrayA, arrayA.length+arrayB.length);
    System.arraycopy (arrayB, 0, result, arrayA.length, arrayB.length);
    return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM