1. 泛型的理解和好处
1.1 看一个需求
1)请编写程序,在ArrayList中,添加3个Dog对象 2) Dog对象含有name和age,并输出name和age(要求使用getXxx())
public class Generic01 {
public static void main(String[] args) {
ArrayList arrayList = new ArrayList();
arrayList.add(new Dog("小黑", 2));
arrayList.add(new Dog("小白", 4));
arrayList.add(new Dog("小青", 6));
arrayList.add(new Cat("小花猫", 8));
for (Object o : arrayList) {
Dog dog = (Dog) o;
System.out.println(dog.getName() + "-" + dog.getAge());
}
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
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;
}
}
class Cat {
private String name;
private int age;
public Cat(String name, int age) {
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;
}
}
- 假如不小心添加了一只猫,在上面代码的基础上添加如下
class Cat {
private String name;
private int age;
public Cat(String name, int age) {
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;
}
}
- 运行报错,类型转换异常
1.2 使用传统方法的问题分析
- 不能对加入到集合ArrayList中的数据类型进行约束(不安全)。
- 遍历的时候,需要进行类型转换,如果集合中的数据量较大,对效率有影响。
1.3 泛型快速体验-用泛型来解决前面的问题
public class Generic02 {
public static void main(String[] args) {
ArrayList<Dog> arrayList = new ArrayList<Dog>();
arrayList.add(new Dog("小黑", 2));
arrayList.add(new Dog("小白", 4));
arrayList.add(new Dog("小青", 6));
for (Dog dog : arrayList) {
System.out.println(dog.getName() + "-" + dog.getAge());
}
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
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;
}
}
class Cat {
private String name;
private int age;
public Cat(String name, int age) {
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;
}
}
1.4 泛型的理解和好处
-
编译时,检查添加元素的类型,提高了安全性。如:在上面添加Cat类时就会报错 -
减少了类型转换的次数,提高效率[说明]
Dog-加入->Object-取出-> Dog
Dog->Dog -> Dog
- 不再提示编译警告
2. 泛型介绍
int a = 10; - 理解:泛(广泛)型(类型)=>
Integer,String,Dog
- 泛型又称参数化类型,是Jdk5.0出现的新特性,解决数据类型的安全性问题。
- 在类声明或实例化时只要指定好需要的具体的类型即可。
- Java泛型可以保证如果程序在编译时没有发出警告,运行时就不会产生
ClassCastException 异常。同时,代码更加简洁、健壮。 - 泛型的作用是:可以在类声明时通过一个标识表示类中某个属性的类型,或者是某个方法的返回值的类型,或者是参数类型。
public class Generic03 {
public static void main(String[] args) {
Person<String> person = new Person<>("兮动人");
person.show();
}
}
class Person<E> {
E s ;
public Person(E s) {
this.s = s;
}
public E f() {
return s;
}
public void show() {
System.out.println(s.getClass());
}
}
class Person1<String> {
String s ;
public Person1(String s) {
this.s = s;
}
public String f() {
return s;
}
}
3. 泛型的语法
3.1 泛型的声明
interface接口<T>{} 和 class类<K,V>{}
说明:
1)其中,T,K,V不代表值,而是表示类型。
2)任意字母都可以。常用T表示,是Type的缩写
3.2 泛型的实例化
List<String> strList = new ArrayList<String>(); [举例说明]Iterator<Customer> iterator = customers.iterator();
3.3 泛型使用举例
- 创建3个学生对象,放入到HashSet中学生对象使用,3个学生放入到 HashMap中,要求Key是name, Value就是学生对象,使用两种方式遍历。
public class GenericExercise {
public static void main(String[] args) {
System.out.println("=======HashSet方式存储========");
HashSet<Student> students = new HashSet<>();
students.add(new Student("xdr", 25));
students.add(new Student("jack", 26));
students.add(new Student("lucy", 27));
for (Student student : students) {
System.out.println(student);
}
System.out.println("=======HashMap方式存储========");
HashMap<String, Student> hashMap = new HashMap<String, Student>();
hashMap.put("tom", new Student("tom", 20));
hashMap.put("jerry", new Student("jerry", 21));
hashMap.put("mike", new Student("mike", 22));
Set<Map.Entry<String, Student>> entries = hashMap.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());
}
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
4. 泛型使用的注意事项和细节
interface List<T>{} , public class HashSet<E>{}.. 说明:T,E只能是引用类型,看看下面语句是否正确?
- 给泛型指向数据类型是要求是引用数据类型,不能是基本数据类型
List<Integer> list = new ArrayList<Integer>{};
List<int> list2 = new ArrayList<int>();
- 在给泛型指定具体类型后,可以传入该类型或者其子类类型
public class GenericDetail {
public static void main(String[] args) {
Pig<A> aPig = new Pig<A>(new A());
aPig.f();
Pig<A> bPig = new Pig<A>(new B());
bPig.f();
}
}
class A {}
class B extends A{}
class Pig<E> {
E e;
public Pig(E e) {
this.e = e;
}
public void f() {
System.out.println(e.getClass());
}
}
- 泛型使用形式
ArrayList<Integer> list1 = new ArrayList<Integer>();
List<Integer> list2 = new ArrayList<Integer>();
ArrayList<Integer> list3 = new ArrayList<Integer>();
List<Integer> list4 = new ArrayList<Integer>();
- 如果这样写
List list = new ArrayList(); 默认给它的泛型是【<E> E 就是 Object 】
ArrayList arrayList1 = new ArrayList();
ArrayList<Object> arrayList2 = new ArrayList<>();
5. 泛型练习
- 该类包含:private成员变量name,sal,birthday,其中 birthday为 MyDate 类的对象;
- 为每一个属性定义getter, setter方法;
- 重写toString方法输出name, sal, birthday
- MyDate类包含:private成员变量month,day,year;并为每一个属性定义getter,setter方法;
- 创建该类的3个对象,并把这些对象放入 ArrayList 集合中(ArrayList 需使用泛型来定义),对集合中的元素进行排序,并遍历输出:
排序方式:调用ArrayList的sort方法,传入 Comparator对象[使用泛型],先按照name排序,如果name相同,则按生日日期的先后排序。【即:定制排序】
public class Employee {
private String name;
private double sal;
private MyDate birthday;
public Employee(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getSal() {
return sal;
}
public void setSal(double sal) {
this.sal = sal;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "\nEmployee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
}
public class MyDate implements Comparable<MyDate>{
private int year;
private int month;
private int day;
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 yearMinus = year - o.getYear();
if(yearMinus != 0) {
return yearMinus;
}
int monthMinus = month - o.getMonth();
if(monthMinus != 0) {
return monthMinus;
}
return day - o.getDay();
}
}
public class GenericExercise02 {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee("tom", 20000, new MyDate(1980,12,11)));
employees.add(new Employee("jack", 12000, new MyDate(2001,12,12)));
employees.add(new Employee("tom", 50000, new MyDate(1980,12,10)));
System.out.println("employees=" + employees);
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee emp1, Employee emp2) {
if(!(emp1 instanceof Employee && emp2 instanceof Employee)) {
System.out.println("类型不正确..");
return 0;
}
int i = emp1.getName().compareTo(emp2.getName());
if(i != 0) {
return i;
}
return emp1.getBirthday().compareTo(emp2.getBirthday());
}
});
System.out.println("==对雇员进行排序==");
System.out.println(employees);
}
}
6. 自定义泛型类
class 类名 <T, R...> {
成员
}
- 普通成员可以使用泛型(属性、方法)
- 使用泛型的数组,不能初始化
- 静态方法中不能使用类的泛型
- 泛型类的类型,是在创建对象时确定的(因为创建对象时,需要指定确定类型)
- 如果在创建对象时,没有指定类型,默认为Object
Tiger<Double,String,Integer> g = new Tiger<>("xdr");
g.setT(10.9);
g.setT("yy");
System.out.println(g);.
Tiger g2 = new Tiger("xdr~~");
g2.setT("yy");
System.out.println("g2=" + g2);
class Tiger<T, R, M> {
public Tiger(T t, R r, M m) {
this.t = t;
this.r = r;
this.m = m;
}
public Tiger(String name) {
this.name = name;
}
}
7. 自定义泛型接口
interface 接口名<T, R...> {
}
- 接口中,静态成员也不能使用泛型(这个和泛型类规定一样)
- 泛型接口的类型,在继承接口或者实现接口时确定
- 没有指定类型,默认为Object
interface IA extends IUsb<String, Double> {
}
class AA implements IA {
@Override
public Double get(String s) {
return null;
}
@Override
public void hi(Double aDouble) {
}
@Override
public void run(Double r1, Double r2, String u1, String u2) {
}
}
class BB implements IUsb<Integer, Float> {
@Override
public Float get(Integer integer) {
return null;
}
@Override
public void hi(Float aFloat) {
}
@Override
public void run(Float r1, Float r2, Integer u1, Integer u2) {
}
}
class CC implements IUsb {
@Override
public Object get(Object o) {
return null;
}
@Override
public void hi(Object o) {
}
@Override
public void run(Object r1, Object r2, Object u1, Object u2) {
}
}
interface IUsb<U, R> {
int n = 10;
R get(U u);
void hi(R r);
void run(R r1, R r2, U u1, U u2);
default R method(U u) {
return null;
}
}
8. 自定义泛型方法
- 基本语法
修饰符<T,R…>返回类型 方法名(参数列表){} - 注意细节
1.泛型方法,可以定义在普通类中,也可以定义在泛型类中 2.当泛型方法被调用时,类型会确定 3.public void eat(E e){} ,修饰符后没有<T,R…> eat方法不是泛型方法,而是使用了泛型
public class CustomMethodGeneric {
public static void main(String[] args) {
Car car = new Car();
car.fly("宝马", 100);
System.out.println("==============");
car.fly(100.1, 100);
Fish<String, ArrayList> fish = new Fish<>();
fish.hello(new ArrayList(),1.1f);
}
}
class Car {
public void run() {
}
public<T, R> void fly(T t, R r) {
System.out.println(t.getClass());
System.out.println(r.getClass());
}
}
class Fish<T, R> {
public void run() {
}
public<U, M> void eat(U u, M m){
}
public void hi(T t) {
}
public<K> void hello(R r, K k) {
System.out.println(r.getClass());
System.out.println(k.getClass());
}
}
- 练习:下面代码是否正确,如果有错误,修改正确,并说明输出什么?
public class CustomMethodGenericExercise {
public static void main(String[] args) {
Apple<String,Integer,Double> apple = new Apple<>();
apple.fly(10);
apple.fly(new Dog());
}
}
class Apple<T,R,M>{
public<E> void fly(E e){
System.out.println(e.getClass().getSimpleName());
}
public void run(M m){}
}
class Dog {}
9. 泛型的继承和通配符
- 泛型不具备继承性
List<Object> list = new ArrayList<String>();
<?> :支持任意泛型类型<? extends A> :支持A类以及A类的子类,规定了泛型的上限<? super A> :支持A类以及A类的父类,不限于直接父类,规定了泛型的下限
public class GenericExtends {
public static void main(String[] args) {
Object o = new String("xdr");
ArrayList<Object> list1 = new ArrayList<>();
ArrayList<String> list2 = new ArrayList<>();
ArrayList<AA> list3 = new ArrayList<>();
ArrayList<BB> list4 = new ArrayList<>();
ArrayList<CC> list5 = new ArrayList<>();
printCollection1(list1);
printCollection1(list2);
printCollection1(list3);
printCollection1(list4);
printCollection1(list5);
printCollection2(list3);
printCollection2(list4);
printCollection2(list5);
printCollection3(list1);
printCollection3(list3);
}
public static void printCollection1(List<?> c) {
for (Object object : c) {
System.out.println(object);
}
}
public static void printCollection2(List<? extends AA> c){
for (Object object : c) {
System.out.println(object);
}
}
public static void printCollection3(List<? super AA> c) {
for (Object object : c) {
System.out.println(object);
}
}
}
class AA {}
class BB extends AA {
}
class CC extends BB {
}
- 练习:
定义个泛型类 DAO,在其中定义一个Map成员变量,Map的键为String类型,值为T类型。 分别创建以下方法: (1) public void save(String id,T entity) :保存T类型的对象到Map成员变量中 (2) public T get(String id) :从 map中获取id对应的对象 (3) public void update(String id,T entity) :替换map 中key为id的内容,改为entity对象 (4) public List<T> list() :返回map中存放的所有T对象 (5) public void delete(String id) :删除指定id对象 - 定义一个User 类:该类包含:private成员变量(int类型)id, age; (String类型)name。
- 创建DAO类的对象,分别调用其save、get、update、list、delete方法来操作User对象,使用Junit单元测试类进行测试。
DAO
public class DAO<T> {
private Map<String, T> map = new HashMap<>();
public T get(String id) {
return map.get(id);
}
public void update(String id, T entity) {
map.put(id, entity);
}
public List<T> list() {
List<T> list = new ArrayList<>();
Set<String> keySet = map.keySet();
for (String key : keySet) {
list.add(map.get(key));
}
return list;
}
public void delete(String id) {
map.remove(id);
}
public void save(String id, T entity) {
map.put(id, entity);
}
}
User
public class User {
private int id;
private int age;
private String name;
public User(int id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
@Test
public void testList() {
DAO<User> dao = new DAO<>();
dao.save("001", new User(1,10,"jack"));
dao.save("002", new User(2,18,"tom"));
dao.save("003", new User(3,20,"lucy"));
List<User> list = dao.list();
System.out.println("list=" + list);
dao.update("003", new User(3, 22, "rose"));
dao.delete("001");
System.out.println("===修改数据后====");
list = dao.list();
System.out.println("list=" + list);
System.out.println("===单个获取数据===");
System.out.println("id=003 " + dao.get("003"));
}
|