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

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")); 
主站蜘蛛池模板: 锡林浩特市| 清水河县| 定边县| 安平县| 蓝山县| 手机| 芮城县| 临海市| 武平县| 桦川县| 翁牛特旗| 陆良县| 荆门市| 徐州市| 东乡族自治县| 湄潭县| 石首市| 乾安县| 布尔津县| 紫金县| 海宁市| 类乌齐县| 桦南县| 南部县| 象山县| 腾冲县| 平阳县| 东方市| 塘沽区| 鹿邑县| 新和县| 宜丰县| 岳普湖县| 武宁县| 柳江县| 垫江县| 阿勒泰市| 岑巩县| 太保市| 麻阳| 绥德县|