泛型的小例子
来源:互联网 发布:李逍遥到底爱谁知乎 编辑:程序博客网 时间:2024/05/18 00:47
在JDK文档中,有的类后面跟着一对<>这就表示这个地方可以用泛型的含义
两个小例子:
import java.util.*;public class TestMap { public static void main(String args[]) { Map m1 = new HashMap(); Map m2 = new TreeMap(); //m1.put("one",new Integer(1)); m1.put("one", 1);<span style="white-space:pre"></span>//这个地方使用了自动打包 //m1.put("two",new Integer(2)); m1.put("two", 2); //m1.put("three",new Integer(3)); m1.put("three", 3); //m2.put("A",new Integer(1)); m2.put("A", 1); //m2.put("B",new Integer(2)); m2.put("B", 2); System.out.println(m1.size()); System.out.println(m1.containsKey("one")); System.out.println //(m2.containsValue(new Integer(1))); (m2.containsValue(1)); if(m1.containsKey("two")) { //int i = ((Integer)m1.get("two")).intValue(); int i = (Integer)m1.get("two"); System.out.println(i); } Map m3 = new HashMap(m1); m3.putAll(m2); System.out.println(m3); }}在上面这段程序中没有使用泛型,因此在后面需要对其进行强制转换,例如:int i = (Integer)m1.get("two");其实,意思就是传给Map的是Objects对象,下面对其进行改写:
import java.util.*;public class TestMap2{public static void mian(String[] args) {Map<String,Integer> m1 = new TreeMap<String,Integer>();<span style="white-space:pre"></span>//这个地方使用了泛型,不然的话,两个都是Objects对象Map<String,Integer> m2 = new HashMap<String,Integer>();<span style="white-space:pre"></span>//使用泛型后,只能传进去<span style="font-family: Arial, Helvetica, sans-serif;"><String,Integer>类型对象,顺序不能变</span>m1.put("one",1);<span style="white-space:pre"></span>//这个地方使用了自动打包技术//m1.put("one",new Integer(1));<span style="white-space:pre"></span>//这个地方没有使用自动打包的话,放进去的是Integer对象,所以需要强制转换m1.put("two",2);//m1.put("two",new Integer(2));m1.put("three",3); //m1.put("three",new Integer(3));m2.put("A",1);//m2.put("A",new Integer(1));m2.put("B",1);//m2.put("B",new Integer(2));System.out.println(m1.containsKey("one"));System.out.println(m2.containsValue(1));System.out.println(m1);System.out.println(m2);if(m1.containsKey("two")){//int i = ((Integer)m1.get("two")).intValue(); <span style="white-space:pre"></span>//int i = (Integer)m1.get("two"); <span style="white-space:pre"></span>int i = m1.get("two");<span style="white-space:pre"></span>//这个地方便显示泛型的好处了,不用对其进行强制转换了}Map m3 = new HashMap(m1); <span style="white-space:pre">m3.putAll(m2); System.out.println(m3);</span>}}
0 0
- 泛型的小例子
- 一个泛型的小例子
- 2个java泛型的小例子(技巧):
- “黑马程序员—”泛型的应用小例子
- 接口的小例子
- 动态的小例子
- File的小例子
- ajax的小例子
- AJAX的小例子
- innerHTML 的小例子
- Sqlite 的小例子
- cglib的小例子
- clone的小例子
- awk的小例子
- printf的小例子
- 继承的小例子
- 触发器的小例子
- 一个小的例子
- 函数access和faccessat函数
- java 深克隆clone对象或容器的另一种方法
- 使用GDI+画仪表表盘
- VC++对Access数据库的操作(查询、插入、更新、删除等)
- argc argv
- 泛型的小例子
- ABBYY OCR SDK免费试用了!
- 计算机编程
- QQ通信协议
- 有关myeclipse中引用的project没有在tomcat中编译的解决方法
- RSS FEED的应用
- VC6.0的若干实用小技巧
- LeetCode - Best Time to Buy and Sell Stock III 题解
- 微软之巨变与”国产化“魔咒