使用泛型能提高效率吗?

fyi1106 2008-03-27 08:35:17
如题,在Java里使用泛型是否会省掉类型强制转换,以提高效率?
...全文
215 15 打赏 收藏 转发到动态 举报
写回复
用AI写文章
15 条回复
切换为时间正序
请发表友善的回复…
发表回复
fyi1106 2008-03-29
  • 打赏
  • 举报
回复
总结一下吧,泛型是一种编译时机制,减少了显式的类型转换,使程序更规范,防止出错,但在运行时还是会进行类型转换。
所以对于效率,和显式的类型转换一样。

fyi1106 2008-03-29
  • 打赏
  • 举报
回复
原来如此,还有一个"run-time"类。
rangerheart 2008-03-28
  • 打赏
  • 举报
回复
修改一下,“应该是不同类型参数的范型类都共有一个运行时类”

比如ArrayList<String>和ArrayList<Integer>在运行时是看作同一个类的,然后需要时都是强制类型转换

下面抄了一段原文:
7.1 A Generic Class is Shared by all its Invocations
What does the following code fragment print?
List <String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass());
You might be tempted to say false, but you’d be wrong. It prints true, because all
instances of a generic class have the same run-time class, regardless of their actual type
parameters.
Indeed, what makes a class generic is the fact that it has the same behavior for all
of its possible type parameters; the same class can be viewed as having many different
types.
As consequence, the static variables and methods of a class are also shared among
all the instances. That is why it is illegal to refer to the type parameters of a type
declaration in a static method or initializer, or in the declaration or initializer of a static
variable.
rangerheart 2008-03-28
  • 打赏
  • 举报
回复
根据java的说明,范型的机制只是一种编译时机制,

也就是说在运行时是不认范型和类型参数的,所有类都默认为object然后强制类型转换,所以范型主要还是用来进行编译时检查的。
amos82 2008-03-28
  • 打赏
  • 举报
回复
我以为 关键是减少出错。
ilovemeimei 2008-03-28
  • 打赏
  • 举报
回复
做应用的细枝末节的效率问题就不用考虑了,做系统的考虑的问题。要抓矛盾的主要方面
ChocooM 2008-03-28
  • 打赏
  • 举报
回复
能提高
try_hard_2008 2008-03-28
  • 打赏
  • 举报
回复
学习中。。
hoszone 2008-03-28
  • 打赏
  • 举报
回复
学习
约翰羊 2008-03-28
  • 打赏
  • 举报
回复
同意楼上
yibunengjing 2008-03-27
  • 打赏
  • 举报
回复
最大的用处就是防止出错,对于效率没有任何的提高
kevinchj 2008-03-27
  • 打赏
  • 举报
回复
确定:某些时候提高效率,不明显。
主要是出于安全,和防止出错。
kokobox 2008-03-27
  • 打赏
  • 举报
回复
提高效率,虽然有的时候用肉眼看不出来...........
fuyou001 2008-03-27
  • 打赏
  • 举报
回复
防止出错,提高效率!
healer_kx 2008-03-27
  • 打赏
  • 举报
回复
C#可以,但是据说Java的不能。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧