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

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>(); 
When using var with generics, ensure that you pass the relevant data types within the angular brackets on the right-hand side of the assignment, so that you don't lose type safety.

Now, it's time for our next code check.

主站蜘蛛池模板: 沅江市| 宁强县| 荥阳市| 湖口县| 和顺县| 金堂县| 运城市| 焦作市| 巴青县| 乌鲁木齐市| 莱州市| 威宁| 丹江口市| 韶关市| 常德市| 缙云县| 江北区| 德阳市| 桂东县| 湖州市| 康平县| 泗水县| 修水县| 五河县| 伊金霍洛旗| 密山市| 嫩江县| 英超| 武威市| 华宁县| 宜兰市| 砀山县| 哈巴河县| 旬邑县| 呼玛县| 呈贡县| 德清县| 江北区| 中西区| 江阴市| 连州市|