---
title: "泛型浅析"
author: "TechBirds"
date: "2013-04-27T14:51:00Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2013-04-27T15:01:44Z"
id: 1855902
url: "https://techbirds.iteye.com/blog/1855902"
---

转载：[http://www.2cto.com/kf/201211/169210.html](http://www.2cto.com/kf/201211/169210.html)

# 1.泛型概念

泛型（Generic type 或者 generics）是对 Java 语言的类型系统的一种扩展，以支持创建可以按类型进行参数化的类。可以把类型参数看作是使用参数化类型时指定的类型的一个占位符，就像方法的形式参数是运行时传递的值的占位符一样。可以在集合框架（Collection framework）中看到泛型的动机。

# 2.泛型简单使用

```
	class Name<H>{
		public void getClassName(H c){
			System.out.println(c.getClass().getName());
		}
	}
	@org.junit.Test
	public void testGeneric(){
		//自定义泛型
		new Name<String>().getClassName("2");
		//使用泛型
		Map<String, String> map1=new HashMap<String, String>();
		map1.put("1", "1");
		map1.put("2", "2");
		String s1=map1.get("1");
		//未使用泛型
		Map map2=new HashMap();
		map2.put("1", "1");
		map2.put("1", "1");
		String s2=(String) map2.get("1");
		
		//编译器自动识别
		List<Integer> list=new ArrayList<Integer>();
		list.add(1);
		list.add(2);
		List<?> l=list;
		System.out.println(l.size());//2
	}
```

# 3.泛型好处

消除强制类型转换。 泛型的一个附带好处是，消除源代码中的许多强制类型转换。这使得代码更加可读，并且减少了出错机会。