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

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.

主站蜘蛛池模板: 武汉市| 南宁市| 中宁县| 康马县| 西林县| 喀喇沁旗| 大英县| 洪洞县| 毕节市| 正镶白旗| 资中县| 延长县| 泊头市| 来凤县| 青河县| 新建县| 黄龙县| 遵义县| 南召县| 红原县| 怀仁县| 河源市| 施秉县| 疏勒县| 阿坝| 抚顺市| 苏尼特左旗| 民权县| 海门市| 滨海县| 舟山市| 同江市| 黔东| 西盟| 得荣县| 罗平县| 张家界市| 成武县| 武乡县| 汕头市| 阿瓦提县|