This week's book giveaway is in the OCPJP forum. We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line! See this thread for details.
I am reading through a a tutorial on generic programming, and, my first step towards that is the apparently classic example involving a Pair.
1. Is it possible to return an array, or a collection of objects?
Somehow I have a feeling that I can't use instanceOf with generic programming, is this true?
2. How is it possible to implement a generic swap algorithm, since for example, String and (wrapped) primitive data types might use different methods in Java to validate whether they are of the same type, and, to implement Comparable
void Swap(T & a, T & b) //"&" passes parameters by reference
T temp = b;
b = a;
a = temp;
string hello = "world!", world = "Hello, ";
Swap( world, hello );
cout << hello << world << endl; //Output is "Hello, world!"
Jon Camilleri wrote:Somehow I have a feeling that I can't use instanceOf with generic programming, is this true?
Partly, because of how generics are implemented in Java (through type erasure). You cannot write obj instanceof T where T is a type parameter. But you should avoid using instanceof anyway, because there are almost always better ways to solve problems for which you think you need it (you can often use polymorphism instead).
Jon Camilleri wrote:2. How is it possible to implement a generic swap algorithm, ...
That example code you posted is C++. In C++, you have pass-by-reference, and together with templates this makes it easy to write a generic swap method. Java does not have pass-by-reference so the same thing is simply not possible in Java.
Note also that generics in Java do not work in the same way as templates in C++. In C++, a template is really a template: when you use it with concrete arguments for the types, the compiler will generate a new class using those concrete types, which potentially leads to a lot of generated classes. In Java, a generic class is not a template. Just one class is generated with the types erased (i.e. all the generic types become Object). The compiler will check that you use it with the correct types, but at runtime the type information is gone.
Jon Camilleri wrote:3. Can a generic class throw an exception? How?
Ofcourse, in exactly the same way as a non-generic class can. There's nothing special about classes with type parameters that changes anything with regard to exceptions.