《Cracking the Coding Interview》——第14章:Java——题目4
2014-04-26 19:05
495 查看
2014-04-26 19:02
题目:解释下C++里模板和java里泛型的区别?
解法:我很少用java,属于连语法都不过关的程度。所以这个题还真没法详细答,查了些资料以后写了以下几点。
代码:
题目:解释下C++里模板和java里泛型的区别?
解法:我很少用java,属于连语法都不过关的程度。所以这个题还真没法详细答,查了些资料以后写了以下几点。
代码:
// 14.4 tell me about the differences between C++ template and java generics. // Answer: // 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. // 2. java generics can put some restrictions on the <T>, such as <T extends superclass>, whereas this is not practical in C++. // 3. You may use downcast instead of generics, but generics enhance the resuability of code, so is template in C++. import java.util.Vector; public class TestJava<T> { public T data; public TestJava(T data) { // TODO Auto-generated constructor stub this.data = data; } String getType() { return this.data.getClass().getName(); } public static void main(String[] args) { Vector<Integer> v = new Vector<Integer>(); v.add(2); v.add(1); TestJava<Vector<Integer>> testJava = new TestJava<Vector<Integer>>(v); System.out.println(testJava.getType()); System.out.println(v); } }
相关文章推荐
- 《Cracking the Coding Interview》——第14章:Java——题目6
- 《Cracking the Coding Interview》——第14章:Java——题目1
- 《Cracking the Coding Interview》——第14章:Java——题目2
- 《Cracking the Coding Interview》——第14章:Java——题目3
- 《Cracking the Coding Interview》——第14章:Java——题目5
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目4
- 《Cracking the Coding Interview》——第10章:可扩展性和存储空间限制——题目1
- 《Cracking the Coding Interview》——第12章:测试——题目6
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目2
- 《Cracking the Coding Interview》——第3章:栈和队列——题目1
- 《Cracking the Coding Interview》——第4章:树和图——题目1
- 《Cracking the Coding Interview》——第5章:位操作——题目7
- 《Cracking the Coding Interview》——第17章:普通题——题目13
- 《Cracking the Coding Interview》——第18章:难题——题目13
- 《Cracking the Coding Interview》——第7章:数学和概率论——题目7
- 程序员面试题目:Cracking the coding interview 分析与解答
- 《Cracking the Coding Interview》——第8章:面向对象设计——题目8
- 《Cracking the Coding Interview》——第13章:C和C++——题目3
- 《Cracking the Coding Interview》——第1章:数组和字符串——题目3
- 《Cracking the Coding Interview》——第4章:树和图——题目2