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

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")); 
主站蜘蛛池模板: 怀柔区| 长海县| 铁岭市| 波密县| 冕宁县| 乐平市| 临夏县| 车险| 土默特左旗| 沙洋县| 阜南县| 铁岭县| 三都| 道孚县| 安远县| 攀枝花市| 肃宁县| 托克逊县| 靖州| 罗源县| 汾西县| 织金县| 宜都市| 新乡市| 博兴县| 宣城市| 平安县| 吉安市| 阜新市| 青海省| 莆田市| 宁远县| 沅江市| 阿尔山市| 六枝特区| 凌源市| 明溪县| 清镇市| 台中县| 东方市| 赫章县|