Java泛型中的一些困惑 [英] A little confusion in java Generics

查看:41
本文介绍了Java泛型中的一些困惑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

List<String> l=new ArrayList<String>()


List<String> l=new ArrayList();


可以帮助任何人,原则是什么?

谢谢!


Can help anyone help and what is the principle?

Thanks!

推荐答案

只要左侧的Generic设置了类型,就差不多了.

但是,如果不设置左侧值的类型,可能会导致奇怪的情况:value:
That''s pretty much the same as long as the Generic on the left side is set with a type.

But it can lead to strange situations when you do not set the type of the left sided value: value:
List l = new ArrayList<string>();
List<Object> o = l;



在将内容添加到列表中时,这肯定可行,因为String是一个对象.



That certainly works while adding things to the List, because String is an Object.

o.add(new Object());
o.add("String");



但是,当您获取值时,可能会导致行为异常:



But when you''re fetching the values, it can lead to misbehavior:

System.out.println(o.get(0)); // Exception because value(0) is no String.


这篇关于Java泛型中的一些困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆