Assigning values without using usual notation like “this.<Double>getAnything(int flag)”
private <T> T getAnything(int flag) {
Object o = null;
if (flag==0)
o=new String("NewString");
else if (flag==1)
o=new Double(0D);
return (T)o;
}
private void someMethod() {
String s = getAnything(0);
Double d = getAnything(1);
}
in the past it was enough only a return object on the method and a simple cast onthe receiveing type, so with the lacking of generic notation on the receiver object it is much more similar and fast to write, any other hint on this?
I think you’re confusing autoboxing with type inference.
Type inference is when the compiler can tell what type it should use on a generic method on its own, from the variables used when calling the method.
For example if you have the following method:
and then call it like:
the inferred type will be SomeChildClass;
The type can be inferred from the parameters or from the return type, as is in your example. But it’s not always obvious to the compiler what type it should use. If that happens you can force the type by using the method
this.<Double>getAnything(int flag)that you described. This usually happens in situations like this:and calling
In cases like this you may need to force the type parameter.
All this being said, please take into consideration everything that polygenelubricants said as well, as he makes some very good points regarding your code and explains what autoboxing is (it’s related to primitive wrapper classes like Integer for int, and Double for double).