I am pretty new to Generics but from what I understand the two implementations you described of Sport class are not the same. Parameterized types are not polymorphic which means that the Sport<Object> class can only be instantiate with a type Object and not with any other type (even though they are Object too). On the other hand the Sport<T> class can be instantiated with any type (String,Integer,Double or types that you created).
As for the second question. A popular example is the generic Stack implementation. If you implement a Stack using generics (class MyStack<E>) than your stack could hold many types. you can instantiate one stack that will hold String elements and another that will hold Integer elements and so on. The most important thing is that you dont have to worry about type-safety issues (assuming you dont try to interact with legacy code, but that is for a diffrent topic).
I am sure some of the Bartenders and Ranch handers can give a more detailed explanation.
Stanley Walker wrote:1>I knwo that using generics you can create a class template using parameterized type. Just one general question though.
is this similar to
In the first case, your class has a generic type T. In the second case, your class has a generic type Object. Keep in mind, that in the second case, Object is *not* the java.lang.Object class. You just happened to name your generic type with the same name as the Object class -- and in effect, may cause some confusion in your class implementation.
If you want to only allow your class to be instantiated with the object type, consider using bounded types.
Thanks Henry. being new to generics is really confusing at the beginning. what i understood from your answer is that T and Object are equivalant in the context of class declarations : Sport<T> is the same as Sport<Object> only the latter can create confusion when used. So the polymorphism issue is only at methods declarations?
ok now i am even more confused. Thank you for the answers.
let me respond one by one.
lets say i declare ArrayList<Dog> ar=new ArrayList<Dog>(). i can add ar.add(new Poodle()) where Poodle extends Dog cause Poodle is a Dog , right?So going by the same logic,let me explain my confusion.
so if i instantiate Sport as Sport sp=new Sport(arrayList); where arrayList contains string elements, this is wrong??? even though i have declared arrayList as ArrayList<Object> arrayList= new ArrayList<Object>(); and added string elements to it.
If i am wrong in my above understanding please do correct me.
} this is wrong?? compiler would not recognize this as adding any object?please explain.
and by bounded types is this what you are suggesting
class Sport<T extends Object>
Please do help, cause the more i dwelve into generics the more confused i seem to get.
I apologize if the questions are outright stupid.