泛型的小例子

来源:互联网 发布:李逍遥到底爱谁知乎 编辑:程序博客网 时间: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
原创粉丝点击