泛型学习1-将类型参数化

  • 例子代码如下:
  • package com.perficient.javabasic.test;
    
    import java.util.HashMap;
    public class Generic<K, V> {
    	public HashMap<K, V> map = new HashMap<K, V>();
    
    	public void put(K k, V v) {
    		map.put(k, v);
    	}
    
    	public V get(K k) {
    		return map.get(k);
    	}
    	public static void main(String[] args) {
    
    		Generic<String, String> test1 = new Generic<String, String>();
    		test1.put("key1", "The first Value");
    		System.out.println("The value of key1 is:" + test1.get("key1"));
    
    		Generic<Integer, String> test2 = new Generic<Integer, String>();
    		test2.put(1, "The Integer one");
    		System.out.println("The value of 1 is:" + test2.get(1));	
    	}
    }
    


  • 运行结果:
  • The value of key1 is:The first Value
    The value of 1 is:The Integer one
    


  • 总结
  • 泛型可以将参数类型参数化

    你可能感兴趣的:(java)