泛型的引出
但是如果我们不小心添加了其他类进去,如下图,就会报错
传统方法存在的问题及泛型的演示
加了泛型以后, 在遍历的时候 , 可以直接取出Dog类型,而不是Object
泛型的好处
泛型介绍
泛型就是一种可以表示数据类型的数据类型
泛型实例
特别强调:E具体的数据类型在定义Person对象的时候指定,即在编译期间,就确定E是什么类型的了
泛型的语法
泛型应用实例
代码如下
public class Student {
public String name;
public int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
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;
}
}
import java.util.*;
public class TestGeneric02 {
public static void main(String[] args) {
HashSet<Student> students = new HashSet<Student>();
students.add(new Student("小明", 12));
students.add(new Student("小红", 11));
students.add(new Student("小白", 13));
//遍历
for (Student student : students) {
System.out.println("student = " + student);
}
HashMap<String, Student> studentMap = new HashMap<String, Student>();
studentMap.put("tom",new Student("tom",38));
studentMap.put("jerry",new Student("jerry",28));
studentMap.put("smith",new Student("smith",48));
//迭代器 EntrySet
/**
* entrySet源码
* K --> String , V --> Student
* public Set<Map.Entry<K,V>> entrySet() {
* Set<Map.Entry<K,V>> es;
* return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
* }
*/
Set<Map.Entry<String, Student>> entries = studentMap.entrySet();
Iterator<Map.Entry<String, Student>> iterator = entries.iterator();
while (iterator.hasNext()) {
Map.Entry<String, Student> next = iterator.next();
System.out.println(next.getKey() + next.getValue());
}
}
}