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\ generic array creation

This is due to erasure in generic, which posts a limit to generic array creation.

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

class A<E>
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\ incompatible types

We are being protected :)


Anonymous said...

[url=]hip hop jewelry[/url],[url=]hip hop pendants[/url],hip hop watches,[url=]bling bling[/url] ,hip hop,[url=]hip hop chains[/url],hip hop bling,[url=]iced out chains[/url],[url=]wholesale chains[/url]
hip hop jewelry
wholesale hip hop watches
hip hop rings

Anonymous said...

[url=]Club Penguin[/url] provides you with a [url=]Club Penguin Money Maker[/url] that permits you to make a lot of coins in Club Penguin.
[url=]Club Penguin Codes[/url] also provides you with [url=]Club Penguin Trackers[/url] such as a [url=]Club Penguin Aunt Arctic Tracker[/url], a [url=]Club Penguin Cadence Tracker[/url], a [url=]Club Penguin Gary Tracker[/url], a [url=]Club Penguin Band Tracker[/url], a [url=]Club Penguin Rockhopper Tracker[/url], and a [url=]Club Penguin Sensei Tracker[/url].
Finally,[url=]Club Penguin Cheats[/url] provides you with [url=]Club Penguin Bots[/url] and [url=]Club Penguin Mission Cheats[/url] and [url=]Club Penguin Coin Cheats[/url]

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=]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