泛型的小例子

在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>
	}	
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章