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
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
public interface MySetInterface<T> {
public int empty();
}
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;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.