随笔- 509  文章- 0  评论- 151  阅读- 22万 

2014-04-26 19:02

题目:解释下C++里模板和java里泛型的区别?

解法:我很少用java,属于连语法都不过关的程度。所以这个题还真没法详细答,查了些资料以后写了以下几点。

代码:

复制代码
 1 // 14.4 tell me about the differences between C++ template and java generics.
 2 // Answer:
 3 //    1. C++ template can be used on built-in type and user-defined types, java generics can only be used on classes. Integer for int, Double for double.
 4 //    2. java generics can put some restrictions on the <T>, such as <T extends superclass>, whereas this is not practical in C++.
 5 //    3. You may use downcast instead of generics, but generics enhance the resuability of code, so is template in C++.
 6 import java.util.Vector;
 7 
 8 public class TestJava<T> {
 9     public T data;
10 
11     public TestJava(T data) {
12         // TODO Auto-generated constructor stub
13         this.data = data;
14     }
15 
16     String getType() {
17         return this.data.getClass().getName();
18     }
19 
20     public static void main(String[] args) {
21         Vector<Integer> v = new Vector<Integer>();
22         v.add(2);
23         v.add(1);
24 
25         TestJava<Vector<Integer>> testJava = new TestJava<Vector<Integer>>(v);
26         System.out.println(testJava.getType());
27         System.out.println(v);
28     }
29 }
复制代码

 

 posted on   zhuli19901106  阅读(240)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示