- Java 11 and 12:New Features
- Mala Gupta
- 189字
- 2021-07-02 12:26:59
Type inference with generics
Generics were introduced in Java to promote type safety. It enabled developers to specify their intentions of using classes, interfaces, and collection classes with fixed types or a range of types. Violations of these intentions were enforced with compilation errors, rather than runtime exceptions, raising the compliance bar.
For example, the following shows how you would define ArrayList to store String values (repeating <String> is optional, on the right-hand side of the assignment):
List<String> names = new ArrayList<>();
However, replacing List<String> with var will put the type safety of the generics at stake:
var names = new ArrayList<>(); names.add(1); names.add("Mala"); names.add(10.9); names.add(true);
The preceding code allows for the addition of multiple data types to names, which is not the intention. With generics, the preferred approach is to make relevant information available to the compiler, so that it can infer its type correctly:
var names = new ArrayList<String>();
Now, it's time for our next code check.
- 觸·心:DT時代的大數據精準營銷
- Visual C++實例精通
- OpenCV for Secret Agents
- MySQL 8 DBA基礎教程
- VMware vSphere 6.7虛擬化架構實戰指南
- Swift細致入門與最佳實踐
- 單片機C語言程序設計實訓100例
- Python+Tableau數據可視化之美
- Keil Cx51 V7.0單片機高級語言編程與μVision2應用實踐
- Java面試一戰到底(基礎卷)
- 高性能MVVM框架的設計與實現:San
- 跟著迪哥學Python數據分析與機器學習實戰
- Node.js入門指南
- Applied Supervised Learning with Python
- OCA Oracle Database 11g:SQL Fundamentals I:A Real World Certification Guide