1.泛型好处
- 编译时,检查添加元素的类型,提高了安全性
- 减少了类型转换的次数,提高效率
说明:
(1)如果不使用泛型
Dog-加入-Object-取出->Dog //放入到ArrayList会先转化成Object,在取出时,还需要转换成Dog(如果不使用泛型,那么ArrayList默认的泛型均为Object类型)
如下源码:
(2)使用泛型
Dog->Dog->Dog//放入和取出时,不需要类型转换,提高效率。
- 不在提示编译警告
2.泛型语法
3.泛型练习
(1)简单泛型案例1
public class Generic03 {
public static void main(String[] args) {
Person<Integer> person = new Person<>(10);
}
}
class Person<E>{
E s;
public Person(E s) {
this.s = s;
}
public E getS(){
return s;
}
}
(2)案例2
- 创建3个学生对象
- 放入HashMap中,要求Key是String name,Value 就是学生对象
- 使用两种方式遍历
public static void main(String[] args) {
Student student1 = new Student("李四", 20);
Student student2 = new Student("张三", 23);
Student student3 = new Student("王二", 26);
Map<String, Student> m = new HashMap<>();
m.put(student1.getName(),student1);
m.put(student2.getName(),student2);
m.put(student3.getName(),student3);
//第一种遍历方式
Set<Map.Entry<String, Student>> entries = m.entrySet();
for (Map.Entry<String, Student> entry : entries) {
System.out.println(entry.getKey()+":"+entry.getValue());
}
System.out.println("----------------------");
//第二种遍历方式
Set<String> set = m.keySet();
for (String s : set) {
System.out.println(s+":"+m.get(s));
}
}