"Real Artists Ship"

Colin Johnson’s blog


A Question about Java Generics

Generics are a useful feature of the Java programming language, allowing the programmer to create a data structure that is parameterised by a data type. I have a specific question about generics to which I can’t find the answer. Here is the setup: let me know if you have a solution to this.

We can create a class, call it Example, which we plan to use with a number of different types, call these T1, T2 etc. Which of these types gets used depends on a user-specified parameter, call this int p.

Here is a fragment of pseudo-Java showing what I want to do (I have added line numbers for later discussion).

1. Example X; //note I haven't parameterised the generic yet
2. switch (p){
3. case 1:
4.   <T1>X = new Example(blah blah blah);
5. break;
6. case 2:
7.   <T2>X = new Example(blah blah blah);
8. break;
9. }
10. X.printAll();
11. X.anotherGeneralMethod();

The difficulty here is that I cannot get how to code the idea suggested by lines 4 and 7. I need to find a way of declaring an unparameterised generic, and then parameterising it later. Is there such a way? The only way I have found to do this so far is to duplicate (or similar) the code in lines 9 and 10 to within each case in the switch statement.

I have read about the notion of wildcards, perhaps this is what I need—but I can’t see how to do the later concretization. Similar arguments apply with using Object at declaration.

Leave a Reply