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

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.

主站蜘蛛池模板: 金华市| 佛冈县| 远安县| 彭水| 陆丰市| 醴陵市| 乌审旗| 兴安盟| 从化市| 东港市| 上饶县| 丰宁| 张掖市| 忻城县| 武胜县| 绥化市| 平谷区| 湟源县| 沧源| 永城市| 梧州市| 金川县| 满城县| 阳谷县| 富顺县| 北京市| 禹城市| 金阳县| 安福县| 乌海市| 灵璧县| 包头市| 富蕴县| 巴青县| 柳州市| 祁连县| 上饶县| 金秀| 仁寿县| 龙泉市| 合阳县|