简体   繁体   English

警告:[使用通用数组时未选中]未选中的强制类型转换

[英]warning: [unchecked] unchecked cast while using Generic Array

I am creating my own set class . 我正在创建自己的固定课程。 But At the beginning , I take a warning. 但是,一开始,我会发出警告。 I use in this link How to create a generic array? 我在此链接中使用如何创建通用数组? . But I have already take warning. 但是我已经警告过了。

This is my warning message: 这是我的警告消息:

MySet.java:11: warning: [unchecked] unchecked cast
        data = (T[]) new Object[10];
                     ^
  required: T[]
  found:    Object[]
  where T is a type-variable:
    T extends Object declared in class MySet
1 warning

This is my beginner code: 这是我的初学者代码:

Main.java Main.java

public class Main{

    public static void main(String[] args){

        MySet<Integer> a = new MySet<Integer>();

        System.out.printf("empty or not = %d\n",a.empty());

    }

}

MySetInterface.java MySetInterface.java

public interface MySetInterface<T> {
    public int empty();
}

MySet.java MySet.java

public class MySet<T> implements MySetInterface<T>{

private T[] data;
private int used;
private int capacity;

public MySet(){

    used = 0;
    capacity = 1024;
    data = (T[]) new Object[10];
}

public int empty(){

    if(used == 0){
        return 1;
    }
    else{
        return 0;
    }

}

If I use 如果我用

@SuppressWarnings("unchecked")
        data = (T[]) new Object[10];

I take this error message now: 我现在收到此错误消息:

MySet.java:12: error: <identifier> expected
        data = (T[]) new Object[10];
            ^
1 error

If you read the answer to the question that you provided it gives a very thorough explanation as to why the warning is shown and it also provided a valid workaround. 如果您阅读了所提供问题的答案,则将对为何显示警告给出非常详尽的解释,并且还提供了有效的解决方法。

The above code have the same implications as explained above. 上面的代码具有与上述相同的含义。 If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. 如果您注意到了,当您将类型转换转换为未知组件类型的数组时,编译器将在此处向您发出未经检查的强制转换警告。 That means, the cast may fail at runtime. 这意味着强制转换可能会在运行时失败。 For eg, if you have that code in the above method: 例如,如果您在上述方法中具有该代码:

Suggested typesafe code. 建议的类型安全代码。

public <E> E[] getArray(Class<E> clazz, int size) {
    @SuppressWarnings("unchecked")
    E[] arr = (E[]) Array.newInstance(clazz, size);

    return arr;
}

Explanation is provided in the answer 答案中提供了解释

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

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