Creating an array of generics in Java

I was messing around with creating a generic Bag collection in Java that’d be backed by an array. It turns out that you can’t do this for a number of interesting reasons…

In Java (and C#), arrays are covariant. This means that if Apple is a subtype of Fruit, then Apple[] will also be a subtype of Fruit[]. Pretty straightforward. That means this will compile:

Apple[] appleArray = new Apple[10];
appleArray[0] = new Apple();
Fruit[] fruitArray = appleArray;    //Spot the problem?

If you’re like me, you didn’t think too hard about this, and assumed you could do the same with parameterized types, i.e. generics. Thanksfully you can’t, because that code is unsafe. It will throw an ArrayStoreException at runtime which we’d have to handle.

Wouldn’t it be great if we could guarantee type safety at compile time?

Generics are safer

Unlike arrays, generics are invariant, which means that Apple being a subtype of doesn’t matter: a List<Apple> is different than a List<Fruit>. The generic version of the code above is illegal:

Vector<Apple> apples = new Vector();
Vector<Fruit> fruits = apples;       //Compile-time error

You can’t cast it, either:

Vector<Apple> apples = new Vector();
Vector<Fruit> fruits = (Vector<Fruit>)apples; //Still a compile-time error!

By making generics invariant, we guarantee safe behavior at compile time, which is a much cheaper place to catch errors. (This is one of the big reasons developers get excited about generics.)

So why are arrays and generics mutually exclusive?

In Java, generics have their types erased at compile time. This is called type erasure. Type erasure means a couple of things happen at compile time:

  • Generic types are boiled down to their raw types: you cannot have a Derp and a Derp<T> in the same package.
  • A method that has a parameterized type overload won’t be compile: a class with methods popFirst(Derp<T> derp) and popFirst(Derp derp) won’t compile.
  • Runtime casts are inserted invisibly by the compiler to ensure runtime type safety. (This means there’s no performance benefit to generics in Java!)

Java’s implementation of generic types is clumsy, and was done to maintain backward-compatibility in the bytecode between Java 5 and Java 4.

Other high-level languages (like C#) implement generics very differently, which means none of the three caveats above apply. Generics in full-stack implementations do net performance gains along with those type-safety guarantees.

To recap, in Java:

  • Arrays require type information at compile time
  • Generics have their types erased at compile time

Therefore you cannot create arrays of parameterized types in Java.

Further reading

3 thoughts on “Creating an array of generics in Java

  1. Thank you for your very clear description of the steps to download from my old but still very useful Olympus VN-4100 PC digital voice recorder. I’d been downloading it to an ancient, ancient computer (I live in Ha Noi), but it caught fire, and I have yet to repair the wires. I needed to download to my Windows 7 laptop, which I did from the company Web page, but of course I couldn’t get the download to work.

    Your directions were so clear, concise, helpful with the links.

    I was up and running in no time and then went to read your web page, which I found very instructive– good reading for a granny in her 70s, who learned FORTRAN in the very early 1960s, before there a single computer on my college campus. At that time, in Massachusetts, there was a computer at Harvard, at MIT, and at UMass/Amherst.

    Thanks again!
    Warmly
    Lady

    Thank you

  2. It’s soooo cool that you studied FORTRAN in the 60s. It’s still a language that’s in use today in many, many science software libraries, and in insurance. Even today, it’s a language that’s hard to beat for certain things.

    If you have some time, listen to this podcast. One of the segments is on FORTRAN, and how one young developer fresh out of school learned to love the language.

    http://thisdeveloperslife.com/post/2-0-7-dinosaurs

    Back then, was programming considered “women’s work”? I’ve heard that it was, which is a big change from today where 9/10 programmers are men. I think the profession loses out because of it. How can we be better as a profession if half the population isn’t heard?

  3. I think it may be true that the people first doing data entry were women, though I don’t know about programming.

    As for studying FORTRAN, I also can’t say, since I went to a women’s college (Mount Holyoke) known in the late 1950s and early 1960s for its emphasis on mathematics and science. That’s the reason I went there. When I was in public high school in Virgina during the late 1950s, a girl had to fight to be allowed to study trig and solid geometry. I regret that I chose not to go on that college field trip to UMass/Amherst to see the only computer west of Boston. Perhaps I was too worried about trying to get my mind around FORTRAN.

    Many years later, in the mid-late 1970s, I was head of emergency mental health services for four counties in southeast Ohio. We used volunteers from Ohio University and then turned our training manual into a book, which as far as I know was the first computerized book in Ohio. We published the book with Ohio University’s Computer Services Department and were able to do so because one of the key computer scientists at OU was married to our deputy director.

    If I remember correctly, Bill Angell was working on what became bar codes. I remember one evening Bill and Myra came to my farm house at the end of a dead-end road in the Ohio hills and brought a computer (by then we had electricity) and set up a game, which (if I remember correctly) was rather like ping-pong on a screen. I’m not sure what program Bill used for the manual, but I remember recognizing elements of FORTRAN and doing my share of data entry, even as director, both for the fun of it and to keep track of what we were doing. Plus I did the final editing for the manual on the university’s computer.

    I have lived for many years in Ha Noi, Viet Nam. We first had internet here in about 1996. I had been in the States for a year. By then, Chris Perisho, a young man who had lived with me as a teenager, had set up along with several friends an Internet server, Frognet (The Friendliest Geeks in the Business!, which is still in business). Chris put Netscape on my computer, which must have been the computer that replaced my Kaypro.

    I learned a great deal from Chris, so that when I returned to Viet Nam in 1996, I was, strange to say, one of the most knowledgeable people about the power of e-mail and could describe the Web to Vietnamese leaders as the “library of the world,” which would allow Viet Nam to jump over the long-term, damaging effects of the embargo.

    We have to remember that there was a war here in Viet Nam and that the United States heavily and repeatedly bombed Ha Noi. Viet Nam suffered under an intense US-led, post-war Western embargo, which kept out books, journals, medical information, technical information, any object or machine produced in the West as well as parts for anything patented in the West even if the parts were made in a country not part of the embargo. The list goes on. The embargo and visa policies also kept Vietnamese from traveling to the West.

    Only in 1991 did Ha Noi (the capital) have a phone system that worked and a critical mass of people with telephones. There is no point in having a phone if the phone system doesn’t work, nor is there any point in having a phone if other people you know don’t have phones. Before 1991, we did everything by biking around town and meeting people in person. I carried everything I was working on in my bag (as I still do) because en route to meet someone, I was apt to meet in the street someone else I needed to see. There were no traffic lights, no cars, a rare motorbike, lots of bicycles. I did much of my work from the basket on my bicycle as I stood in the street, I still do today.

    By 1996, the phone system set up by the Philippines in 1990-1991 and the Web allowed us to jump from Viet Nam into libraries and organizations across the world. We could download. Of course, the connections were slow, particularly by today’s standards, but they were ever so much faster than traveling to the West, going to some library or organization in the States, standing in the photocopy line, and then back-packing the requested documents or journals back to Viet Nam.

    It took me two years, but in 1998, I was able to persuade the appropriate Vietnamese leaders to allow Vietnamese to post up onto the Web, since publishing on the Web was the same as publishing in print, albeit in a different format. By that time, I could point out that the Vietnamese had citizens here with the programming and other technical expertise to manage the Web, a phone system that worked well, and the ability to implement their own limitations.

    The Web here in Viet Nam is far more open than in China. We have “Uncle” Google, and just about everyone is on Facebook, though not me. I’m too busy doing other things (like writing this comment). The first time I even saw Facebook was two days ago. I think I am the only person in Ha Noi over age two who does not have a cell phone.

    Lady Borton

Leave a Reply

Your email address will not be published. Required fields are marked *