官术网_书友最值得收藏!

Type inference in Java 7

Java 7 introduced type inference for constructor arguments with generics. Consider the following line of code:

List<String> myThings = new ArrayList<String>(); 

In Java 7, the preceding line of code could be replaced with the following:

List<String> myThings = new ArrayList<>();  

The preceding code shouldn't be confused with the following, which is trying to mix the generics with the raw types:

List<String> myThings = new ArrayList();  

Java 7 also allowed type inference to invoke generic methods. For a generic method (say, print()) defined in a class (say, MyClass), the code would be as follows:

class MyClass<T> { 
   public <X> void print(X x) { 
         System.out.println(x.getClass()); 
   } 
}  

The preceding code can be called in either of the following ways (the third line of code uses type inference to infer the type of the argument passed to the print() method):

MyClass<String> myClass = new MyClass<>(); 
myClass.<Boolean>deliver(new Boolean("true"));     
myClass.deliver(new Boolean("true")); 
主站蜘蛛池模板: 永城市| 建平县| 大连市| 阿拉善左旗| 汕尾市| 廉江市| 商南县| 孝感市| 交口县| 华坪县| 英山县| 临泽县| 东乌珠穆沁旗| 台南县| 邵阳县| 清镇市| 吉木乃县| 彰化市| 乌审旗| 调兵山市| 湖北省| 岳阳市| 许昌市| 庆元县| 鹤山市| 遂昌县| 东至县| 诏安县| 鄄城县| 长岭县| 武功县| 读书| 昔阳县| 彰化市| 马龙县| 乐陵市| 新沂市| 安平县| 板桥市| 凭祥市| 灌阳县|