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

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")); 
主站蜘蛛池模板: 壶关县| 灯塔市| 达州市| 巴里| 依兰县| 临夏县| 黄石市| 资兴市| 苏尼特右旗| 健康| 孝感市| 彝良县| 平山县| 兴宁市| 泉州市| 东明县| 金阳县| 大埔区| 句容市| 合肥市| 自贡市| 手游| 和龙市| 兴海县| 朔州市| 姜堰市| 商河县| 新兴县| 威海市| 洛宁县| 乐清市| 昔阳县| 凤庆县| 湘阴县| 政和县| 曲阜市| 桦南县| 和田县| 顺平县| 会理县| 延吉市|