wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes a doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "a doubt" Watch "a doubt" New topic
Author

a doubt

krishna vijay
Greenhorn

Joined: Aug 10, 2007
Posts: 14
I am confused about when should we use wildcard <?> and when should we use type parameters <T>? Can someone show me with examples?
Yohan Liyanage
Ranch Hand

Joined: Aug 17, 2007
Posts: 132

Wildcard Symbol '?' is used in situations which involves Generic Collections, like the following:

Say for example that you have a method, for which you should pass an argument which is a list of objects whose class is 'MySuper', or any subclass of 'MySuper'. In that case, you could write the method definition as follows:



(Note that writing just List<MySuper> will not work.)

On the other hand, 'T' is used when you are writing your own Generic Types (that is, classes which can be instantiated for specific types). T stands for Type in convention, which means that it is used for non-collections. Consider the following example:

Suppose you are writing a generic class called MyGeneric, which could be instantiated for any type you want. The class declaration will be as follows:



Within the class, you could use 'T' to represent the runtime type which a user chooses. For example, think that you needs to create a variable for whatever the type user selects : then you could use T to create a variable for that.



If the user instantiates your class using MyGeneric<int>, then T will be 'int' for that instance. If they use MyGeneric<Object>, T will be Object for that instance.

Note that there is another companion to 'T' which is 'E': representing Element. It stands for collections.

E and T are just conventions.


Yohan Liyanage
http://blog.yohanliyanage.com
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: a doubt
 
Similar Threads
Problem with using PrintWriter inside a JSP
generics
checkbox
writing into xml as wells as into tables
web.xml causes 404 error