- 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.
- C++面向?qū)ο蟪绦蛟O(shè)計(第三版)
- Raspberry Pi for Python Programmers Cookbook(Second Edition)
- Python自動化運維快速入門(第2版)
- ASP.NET Core Essentials
- TypeScript圖形渲染實戰(zhàn):基于WebGL的3D架構(gòu)與實現(xiàn)
- Data Analysis with Stata
- 軟件架構(gòu):Python語言實現(xiàn)
- JavaCAPS基礎(chǔ)、應(yīng)用與案例
- Mastering Data Mining with Python:Find patterns hidden in your data
- 詳解MATLAB圖形繪制技術(shù)
- 大學計算機基礎(chǔ)實驗指導(dǎo)
- 遠方:兩位持續(xù)創(chuàng)業(yè)者的點滴思考
- 程序員的成長課
- 黑莓(BlackBerry)開發(fā)從入門到精通
- Spring MVC Blueprints