-
Notifications
You must be signed in to change notification settings - Fork 0
Generic
Generics implement the concept of parameterized types, which allow multiple types.
One of the things you often want to do is return multiple objects from a method call. The return statement only allows you to specify a single object, so the answer is to create an object that holds the multiple objects that you want to return.
This concept is called a tuple, and it is simply a group of objects wrapped together into a single object. The recipient of the object is allowed to read the elements but not put new ones in.(This concept is also called a Data Transfer Object or Messenger.)
Tuples can typically be any length, but each object in the tuple can be of a different type.
You can also parameterize methods within a class. The class itself may or may not be generic-this is independent of whether you have a generic method.
A generic method allows the method to vary independently of the class. As the guideline, you should use generic methods "whenever you can." In addition, if a method is static, it has no access to the generic type parameters of the class, so if it needs to use genericity it must be a generic method.
Note that with a generic class, you must specify the type parameters when you instantiate the class. But with a generic method, you don't usually have to specify the parameter types, because the compiler can figure that out for you. This is called type argument inference.