mercredi 6 mai 2015

Why can't I create a generic array in Java?

Well, I have read a lot of answers to this question, but I have a more specific one. Take the following snippet of code as an example.

public class GenericArray<E>{
    E[] s= new E[5];
}

After type erasure, it becomes

public class GenericArray{
    Object[] s= new Object[5];
}

This snippet of code seems to work well. Why does it cause a compile-time error?

In addition, I have known from other answers that the following codes work well for the same purpose.

public class GenericArray<E>{
    E[] s= (E[])new Object[5];
}

I've read some comments saying that the piece of code above is unsafe, but why is it unsafe? Could anyone provide me with a specific example where the above piece of code causes an error?

Aucun commentaire:

Enregistrer un commentaire