Forums Register Login

a doubt

+Pie Number of slices to send: Send
I am confused about when should we use wildcard <?> and when should we use type parameters <T>? Can someone show me with examples?
+Pie Number of slices to send: Send
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.
Don't touch me. And dont' touch this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1055 times.
Similar Threads
checkbox
generics
web.xml causes 404 error
Problem with using PrintWriter inside a JSP
writing into xml as wells as into tables
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 29, 2024 04:33:56.