---
title: "泛型的类型擦除"
author: "C_SHaDow"
date: "2012-12-08T18:55:05Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2012-12-08T18:55:05Z"
id: 1744231
url: "https://c-shadow.iteye.com/blog/1744231"
---

当把一个具有泛型信息的对象赋给另一个没有泛型信息的变量时，所有在尖括号之间的类型信息都将被丢弃。这种擦除不仅会擦除使用该Java类时传入的类型实参，而且会擦除所有的泛型信息，也就是擦除所有尖括号里的信息。

```
import java.util.ArrayList;
import java.util.List;

public class ErasureTest {

	public static void main(String[] args) {
		Apple<Integer> a = new Apple<Integer>(6);
		for(String apple : a.getApples()) {
			System.out.println(apple);
		}
		Apple b = a;
		// 提示“不兼容的类型”编译错误
		for(String apple : b.getApples()) {
			System.out.println(apple);
		}
	}

}

class Apple<T extends Number> {
	T size;

	public Apple(T size) {
		this.size = size;
	}

	public String toString() {
		return "Apple[size=" + size + "]";
	}
	
	public List<String> getApples() {
		List<String> list = new ArrayList<String>();
		for (int i = 0; i < 3; i++) {
			list.add(new Apple<Integer>(10*i).toString());
		}
		return list;
	}
}
```