Generic Methods Core Java

In the preceding section, you have seen how to define a generic class. You can alsodefine a single method with type parameters.

This method is defined inside an ordinary class, not inside a generic class. However, it isa generic method, as you can see from the angle brackets and the type variable. Notethat the type variables are inserted after the modifiers (public static, in our case) andbefore the return type.

You can define generic methods both inside ordinary classes and inside generic classes. When you call a generic method, you can place the actual types, enclosed in anglebrackets, before the method name:

In this case (and indeed in most cases), you can omit the <String> type parameter fromthe method call. The compiler has enough information to infer the method that youwant. It matches the type of names (that is, String[]) against the generic type T[] anddeduces that T must be String. That is, you can simply call

In almost all cases, type inference for generic methods works smoothly. Occasionally,the compiler gets it wrong, and you’ll need to decipher an error report. Consider thisexample:

The error message is: “found: java.lang.Number & java.lang.Comparable<? extendsjava .lang .Number & java.lang .Comparable <?>>, required: double”. You will learn later in this chapter how todecipher the “found” type declaration. In a nutshell, the compiler autoboxed the parameters into a Double and two Integer objects, and then it tried to find a common supertype ofthese classes. It actually found two: Number and the Comparable interface, which is itself ageneric type. In this case, the remedy is to write all parameters as double values.

In plain English, you can assign the result to Object, Serializable, or Comparable.

C++ NOTE: In C++, you place the type parameters after the method name. That can lead tonasty parsing ambiguities. For example, g(f<a,b>(c)) can mean “call g with the result off<a,b>(c)”, or “call g with the two boolean values f<a and b>(c)”.

Face Book Twitter Google Plus Instagram Youtube Linkedin Myspace Pinterest Soundcloud Wikipedia

All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd Protection Status

Core Java Topics