- 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"));
推薦閱讀
- 多媒體CAI課件設計與制作導論(第二版)
- Mastering PHP Design Patterns
- 小程序,巧運營:微信小程序運營招式大全
- Magento 1.8 Development Cookbook
- Mastering Drupal 8 Views
- 批調度與網絡問題的組合算法
- C語言開發基礎教程(Dev-C++)(第2版)
- Mastering Web Application Development with AngularJS
- JavaScript機器人編程指南
- Mockito Essentials
- Drupal 8 Development:Beginner's Guide(Second Edition)
- SQL Server on Linux
- 深入理解Java虛擬機:JVM高級特性與最佳實踐
- Go Systems Programming
- C語言程序設計