一、泛型的设计背景
集合容器类在设计阶段/声明阶段不能确定这个容器到底实际存的是什么类型的对象,所以在JDK1.5之前只能把元素类型设计为Object,JDK1.5之后使用泛型来解决。因为这个时候除了元素的类型不确定,其他的部分是确定的,例如关于这个元素如何保存,如何管理等是确定的,因此此时把元素的类型设计成一个参数,这个类型参数叫做泛型。Collection,List,ArrayList 这个就是类型参数,即泛型。
二、泛型的概念
- 所谓泛型,就是允许在定义类、接口时通过一个标识表示类中某个属性的类型或者是某个方法的返回值及参数类型。这个类型参数将在使用时(例如,继承或实现这个接口,用这个类型声明变量、创建对象时)确定(即传入实际的类型参数,也称为类型实参)。
- 从JDK1.5以后,Java引入了“参数化类型(Parameterized type)”的概念,允许我们在创建集合时再指定集合元素的类型,正如:List,这表明该List只能保存字符串类型的对象。
- JDK1.5改写了集合框架中的全部接口和类,为这些接口、类增加了泛型支持,从而可以在声明集合变量、创建集合对象时传入类型实参。
三、为什么要有泛型
- 解决元素存储的安全性问题,不会弄错。
- 解决获取数据元素时,需要类型强制转换的问题。
//在集合中使用泛型之前的情况:
@Test
public void test1() {
ArrayList list = new ArrayList();
//需求:存放学生的成绩
list.add(78);
list.add(76);
list.add(89);
list.add(88);
//问题一:类型不安全
// list.add("Tom");
for (Object score : list) {
//问题二:强转时,可能出现ClassCastException
int stuScore = (Integer) score;
System.out.println(stuScore);
}
}
Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生ClassCastException异常。同时,代码更加简洁、健壮。
四、集合中使用泛型举例
* 1.jdk 5.0新增的特性
* <p>
* 2.在集合中使用泛型
* 总结:
* ①集合接口或集合类中在jdk5.0时都修改为带泛型的结构。
* ②在实例化集合类时,可以指明具体的泛型类型。
* ③指明完以后,在集合类或接口中凡是定义类或接口时,内部结构(比如:方法、构造器、属性等)使用到类的泛型的位置,都指定为实例化的泛型类型。
* 比如:add(E e) ---> 实例化以后:add(Integer e)
* ④注意点:泛型的类型必须是类,不能是基本数据类型。需要用到基本数据类型的位置,拿包装类替换。
* ⑤如果实例化时没有指明泛型的类型。默认类型为java.lang.Object类型。
//在集合中使用泛型的情况:
@Test
public void test2() {
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(78);
list.add(76);
list.add(89);
list.add(88);
//编译时,就会进行类型检车,保证数据的安全
// list.add("Tom");
//方式一:
// for (Integer score : list) {
// //避免了强转操作
// int stuScore = score;
// System.out.println(stuScore);
// }
//方式二:
Iterator<Integer> iterator = list.iterator();
while (iterator.hasNext()) {
int stuScore = iterator.next();
System.out.println(stuScore);
}
}
//在集合中使用泛型的情况:以HashMap为例
@Test
public void test3() {
// Map<String, Integer> map = new HashMap<String, Integer>();
//jdk7新特性:类型推断
Map<String, Integer> map = new HashMap<>();
map.put("Tom", 87);
map.put("Jerry", 87);
map.put("Jack", 67);
// map.put(123,"ABC");
//泛型的嵌套
Set<Map.Entry<String, Integer>> entry = map.entrySet();
Iterator<Map.Entry<String, Integer>> iterator = entry.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Integer> e = iterator.next();
String key = e.getKey();
Integer value = e.getValue();
System.out.println(key + "---" + value);
}
}
五、集合中使用泛型的练习
定义一个 Employee 类,
该类包含:private 成员变量 name,age,birthday,其中 birthday 为 MyDate 类的对象;
并为每一个属性定义 getter, setter 方法;
并重写 toString 方法输出 name, age, birthday
MyDate 类包含:
private 成员变量 month,day,year;并为每一个属性定义 getter, setter 方法;
创建该类的 5 个对象,并把这些对象放入 TreeSet 集合中(TreeSet 需使用泛型
来定义),
分别按以下两种方式对集合中的元素进行排序,并遍历输出:
1). 使 Employee 继承 Comparable 接口,并按 name 排序
2). 创建 TreeSet 时传入 Comparator 对象,按生日日期的先后排序。
Employee
public class Employee implements Comparable<Employee> {
private String name;
private int age;
private MyDate birthday;
public Employee() {
}
public Employee(String name, int age, MyDate birthday) {
this.name = name;
this.age = age;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}';
}
@Override
public int compareTo(Employee o) {
return this.name.compareTo(o.name);
}
}
MyDate
public class MyDate implements Comparable<MyDate> {
private int year;
private int month;
private int day;
public MyDate() {
}
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
@Override
public int compareTo(MyDate o) {
//比较年
int minusYear = this.getYear() - o.getYear();
if (minusYear != 0) {
return minusYear;
}
//比较月
int minusMonth = this.getMonth() - o.getMonth();
if (minusMonth != 0) {
return minusMonth;
}
//比较日
return this.getDay() - o.getDay();
}
}
EmployeeTest
public class EmployeeTest {
//问题二:按生日日期的先后排序
@Test
public void test2() {
TreeSet<Employee> set = new TreeSet<>(new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
MyDate b1 = o1.getBirthday();
MyDate b2 = o2.getBirthday();
return b1.compareTo(b2);
}
});
Employee e1 = new Employee("liudehua", 55, new MyDate(1965, 5, 4));
Employee e2 = new Employee("zhangxueyou", 43, new MyDate(1987, 5, 4));
Employee e3 = new Employee("guofucheng", 44, new MyDate(1987, 5, 4));
Employee e4 = new Employee("liming", 51, new MyDate(1954, 8, 12));
Employee e5 = new Employee("liangzhaowei", 21, new MyDate(1978, 12, 4));
set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);
Iterator<Employee> iterator = set.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
//问题一:使用自然排序
@Test
public void test1() {
TreeSet<Employee> set = new TreeSet<>();
Employee e1 = new Employee("liudehua", 55, new MyDate(1965, 5, 4));
Employee e2 = new Employee("zhangxueyou", 43, new MyDate(1987, 5, 4));
Employee e3 = new Employee("guofucheng", 44, new MyDate(1987, 5, 9));
Employee e4 = new Employee("liming", 51, new MyDate(1954, 8, 12));
Employee e5 = new Employee("liangzhaowei", 21, new MyDate(1978, 12, 4));
set.add(e1);
set.add(e2);
set.add(e3);
set.add(e4);
set.add(e5);
Iterator<Employee> iterator = set.iterator();
while (iterator.hasNext()) {
Employee employee = iterator.next();
System.out.println(employee);
}
}
}