Friday, October 31, 2008

Java Generic Array Creation

Consider the following code :-


class A<E>
{
public A<E>[] array = new A<E>[4];
}


We will get the following compilation error :-

C:\Projects\Main\src\test\Main.java:24: generic array creation


This is due to erasure in generic http://en.wikipedia.org/wiki/Generics_in_Java, which posts a limit to generic array creation.

The workaround is simple. Here is the fixed code :-


class A<E>
{
@SuppressWarnings("unchecked")
public A<E>[] array = new A[4];
}


However, is it safe to do so? Yes. Generics are checked at compile-time for type correctness. We still able to receive "protection" from the above code. Consider the following :-


public class Main {
public static void main(String[] args) {
A<String> a = new A<String>();
// We try to do some stupid thing here.
a.array[0] = 0;
}
}


The compiler will prevent us to do "stupid" thing by flagging us :-

C:\Projects\Main\src\test\Main.java:32: incompatible types


We are being protected :)

2 comments:

Anonymous said...

I am the kind of hombre who passions to seek brand-new stuff. Currently I'm making my hold pv panels. I am making it all alone without the help of my men. I am using the net as the only way to acheive this. I ran across a truly amazing site which explains how to build pv panels and wind generators. The web site explains all the steps involved in solar panel construction.

I'm not exactly sure about how accurate the data given there is. If some people over here who had experience with these things can have a see and give your feedback in the page it would be great and I'd highly value it, cauze I really passion [URL=http://apennootje.blogwogin.com/2009/11/10/solar-panel-construction-at-home]solar panel construction[/URL].

Thanks for reading this. U people rock.

Patrick D said...

Hello friend amazing and very interesting blog I really enjoyed reading and I would like to have any update about it and i want to know if you have any blog about kamagra

Followers