- Java 11 and 12:New Features
- Mala Gupta
- 152字
- 2021-07-02 12:27:01
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"));
推薦閱讀
- Android和PHP開發(fā)最佳實踐(第2版)
- 青少年美育趣味課堂:XMind思維導(dǎo)圖制作
- Web程序設(shè)計(第二版)
- MySQL數(shù)據(jù)庫基礎(chǔ)實例教程(微課版)
- 算法訓(xùn)練營:提高篇(全彩版)
- AIRIOT物聯(lián)網(wǎng)平臺開發(fā)框架應(yīng)用與實戰(zhàn)
- Microsoft Azure Storage Essentials
- 現(xiàn)代C++編程實戰(zhàn):132個核心技巧示例(原書第2版)
- Access 2010中文版項目教程
- Java編程從入門到精通
- Python 3 Object:oriented Programming(Second Edition)
- 邊玩邊學(xué)Scratch3.0少兒趣味編程
- 深度學(xué)習(xí)程序設(shè)計實戰(zhàn)
- Developing Java Applications with Spring and Spring Boot
- 大話代碼架構(gòu):項目實戰(zhàn)版