Is this universal auto-boxing?
Assigning values without using the 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, only the returned object was enough for the method and simple cast to the type of reception, so with the absence of general notation on the recipient object, it is much more similar and quick to write, any other hint to this
I think you are misleading autoboxing with output type.
Type inference is when the compiler can determine which type it should use for the general method itself, from the variables used when the method is called.
, :
public <T extends SomeClass> T process(T obj) {
// call some methods of SomeClass on obj to process it here
return obj;
}
:
SomeChildClass a = new SomeChildClass(); // SomeChildClass extends SomeClass
a = process(a);
SomeChildClass;
, . , . , , this.<Double>getAnything(int flag). :
public <T> List<T> getSomeList() {
// implementation
}
public void processList(List<SomeClass> list) {
// implementation
}
processList(getSomeList()); // compiler error: cannot convert List<Object> to List<SomeClass>
.
, , , , , autoboxing ( -, Integer int Double for double).
, , , , - .
Double d = getAnything(0);
// compiles fine, but throws ClassCastException at run time
.
, :
return (T)o; // warning: Type safety: Unchecked cast from Object to T
.
- Java 2nd Edition, 24:
On Typesafe Heterogenic Container
, - , . :
, API, THC, Josh 2006 JavaOne:
public class Favorites { private Map<Class<?>, Object> favorites = new HashMap<Class<?>, Object>(); public <T> void setFavorite(Class<T> klass, T thing) { favorites.put(klass, thing); } public <T> T getFavorite(Class<T> klass) { return klass.cast(favorites.get(klass)); } public static void main(String[] args) { Favorites f = new Favorites(); f.setFavorite(String.class, "Java"); f.setFavorite(Integer.class, 0xcafebabe); String s = f.getFavorite(String.class); int i = f.getFavorite(Integer.class); } }
; int i = f.getFavorite(String.class); ( !).
.
- Java 2nd Edition, 29:
- Neal Gafter Blog -
Autoboxing - say int Integer; autounboxing - . , , .