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

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.

主站蜘蛛池模板: 银川市| 尉氏县| 太白县| 六安市| 松原市| 万盛区| 耒阳市| 龙海市| 肃北| 西畴县| 汝城县| 泰顺县| 元谋县| 磴口县| 荥经县| 盐山县| 柘城县| 尼玛县| 五大连池市| 新疆| 财经| 德惠市| 玉环县| 谢通门县| 屏南县| 永康市| 调兵山市| 吴江市| 罗源县| 阿尔山市| 安陆市| 福建省| 衡东县| 姜堰市| 丹阳市| 罗山县| 石台县| 司法| 济南市| 静乐县| 金秀|