1.基本介绍
public class generic01 {
public static void main(String[] args) {
//1.可以指定存放的元素类型,不符合的会报错
//只能存放Dog及其子类
ArrayList<Dog> list = new ArrayList<Dog>();
list.add(new Dog("q"));
//list.add(new Cat());//错误
//2.dog指定泛型,那类也要指定泛型
Dog<String> dog = new Dog<String>("a");
System.out.println(dog.getClass());
// 等价于,下面的E都是String
// class Dog<String>{
// public String age;
//
// public Dog(String age) {
// this.age = age;
// }
// public E hello(){//
// return this.age;
// }
// }
}
}
class Dog<E>{//E表示定义对象的时候,指定的数据类型
public E age;//E可以是参数类型
public Dog(E age) {//E可以是参数类型
this.age = age;
}
public E hello(){//E可以是返回类型
return this.age;
}
}
class Cat{}
细节:
1. 接口泛型:interface<T>;类泛型class Cat<T,F,G>
2.这里的大写字母表示的是泛型类型,可以是其他字母。
3.泛型只能是引用类型,也就是大写字母只能是引用类型。Integer可以,int不行(Integer是引用类型)。
4.在指定具体类型后,可以传入该类型或者其子类型。
5.可以简写
//简写
HashSet<Student> students1 = new HashSet();
HashSet<Student> students2 = new HashSet<>();
//这样写泛型默认是 object
HashSet students3 = new HashSet();
2.自定义泛型类
细节:
1.普通成员可以使用泛型
2.使用泛型的数组不能初始化
3.静态方法中不能使用类的泛型
4.泛型类的类型,是在创建对象时确定的;如果创建时没有指定类型,默认object
3.自定义泛型接口
1.泛型接口的类型,在继承接口或者实现接口时确定。
2.没有指定类型,默认object。
3.接口中,静态成员也不能使用泛型(接口里所有的变量都是静态的)
public class e3 {
public static void main(String[] args) {
}
}
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;
}
}
//泛型接口的类型,在继承接口或者实现接口时确定。
interface IA extends IUsb<String,Double>{
}
//当我们去实现IA接口时,因为IA在继承Iusb接口时,指定了泛型
//在实现IUsb接口的方法时,就会替换U,R-->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) {
}
}
//实现接口时,直接指定泛型接口的类型
//给U指定Integer给R指定Float
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<Object,Object>{//还是会警告,建议还是写上
@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) {
}
}
4.自定义泛型方法
细节:
1.可以定义在普通类中,也可以定义在泛型类中
2.泛型方法被调用时类型会确定
public class e4 {
public static void main(String[] args) {
Car car = new Car();
car.fly("1",100);
car.fly(1.1,"aa");
}
}
//泛型方法可以定义在普通类
class Car{
public void run(){}//普通方法
public<T,R> void fly(T t,R r){}//泛型方法
}
//泛型方法可以定义在泛型类
class Fish<T,R>{
public void run(){}//普通方法
public<D,A> void eat(D d,A a){}//泛型方法
public void qwq(T t){}//不是泛型方法,只是使用了泛型
}
5.泛型继承和通配符
细节:
1.泛型不具备继承性
public class e6 {
public static void main(String[] args) {
Object o=new String("aa");
List<String> strings = new ArrayList<String>();//正确
//List<Object> strings1 = new ArrayList<String>();错误
//泛型不具备继承性
}
}
2.
<?>支持任意泛型类型
<? extend AA>支持AA类及其子类
<? super AA>支持AA类及其父类,爷爷类,太爷爷类......
public class e6 {
public static void main(String[] args) {
List<Object> list1 = new ArrayList<>();
List<String> list2 = new ArrayList<>();
List<AA> list3 = new ArrayList<>();
List<BB> list4 = new ArrayList<BB>();
List<CC> list5 = new ArrayList<CC>();
// List<?> c,可以是任意科学泛型
qwq(list1);//T
qwq(list2);//T
qwq(list3);//T
qwq(list4);//T
qwq(list5);//T
// qwq1(list1);//F
// qwq1(list2);//F
qwq1(list3);//T
qwq1(list4);//T
qwq1(list5);//T
// qwq2(list);F
// qwq2(list1);F
// qwq2(list2);F
qwq2(list3);
// qwq2(list4);F
}
//List<?>传任何类型的都可以
public static void qwq(List<?> c){
for (Object o :c) {//通配符,object,传任何类型的都可以
System.out.println(o);
}
}
//List<? extends AA>AA类及其子类
public static void qwq1(List<? extends AA> c){
for (Object o :c) {
System.out.println(o);
}
}
//List<? extends AA>AA类及其父类
public static void qwq2(List<? super AA> c){
for (Object o :c) {
System.out.println(o);
}
}
}
class AA{}
class BB extends AA{}
class CC extends AA{}
6.练习
1.
创建3个学生对象
放入HashMap(Key是String name,value是学生对象),hashset中
然后遍历
public class generic02 {
public static void main(String[] args) {
//使用泛型方式给HashSet添加元素
HashSet<Student> students = new HashSet<Student>();
students.add(new Student("a",1));
students.add(new Student("b",2));
students.add(new Student("c",3));
students.add(new Student("d",4));
//遍历
for (Student o :students) {
System.out.println(o);
}
//使用泛型方式给HashMap添加元素
HashMap<String, Student> sm = new HashMap<>();
sm.put("aa",new Student("aa",11));
sm.put("bb",new Student("bb",12));
sm.put("cc",new Student("cc",13));
//迭代器
Set<Map.Entry<String, Student>> entries = sm.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;
}
}
2.
定义Employee类
1)该类包含: private成员变量name,sal,birthday,其中 birthday 为 MyDate 类的对象
2)为每一个属性定义 getter, setter 方法;
3)重写 toString 方法输出 name, sal, birthday
4)MyDate类包含: private成员变量month,day.year; 并为每一个属性定义 getter
setter 方法;
5)创建该类的3 个对象,并把这些对象放入 ArrayList 集合中(ArrayList 需使用泛
型来定义),对集合中的元素进行排序,并遍历输出:
6)排序方式: 调用ArrayList 的 sort 方法,传入Comparator对象[使用泛型],先按照
name排序,如果name相同,则按生日日期的先后排序。[即: 定制排序]
有一定难度,比较经典的泛型使用案例
public class e1 {
public static void main(String[] args) {
ArrayList<Employee> employees = new ArrayList<>();
employees.add(new Employee("a",1000,new MyDate(2002,02,20)));
employees.add(new Employee("b",1000,new MyDate(2002,03,20)));
employees.add(new Employee("c",1000,new MyDate(2002,04,20)));
employees.add(new Employee("a",1000,new MyDate(2002,02,19)));
System.out.println(employees);
System.out.println("对员工排序");
employees.sort(new Comparator<Employee>() {
@Override
public int compare(Employee o1, Employee o2) {
//先验证传入的参数
if (!(o1 instanceof Employee && o2 instanceof Employee)){
System.out.println("类型不正确");
return 0;
}
//比较name
int i=o1.getName().compareTo(o2.getName());
if (i != 0){
return i;
}
//对日期的比较封装到date
return o1.getBirthday().compareTo(o2.getBirthday());
}
});
System.out.println(employees);
}
}
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 "Employee{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
}
class MyDate implements Comparable<MyDate>{
private int month;
private int day;
private int year;
public MyDate(int month, int day, int year) {
this.month = month;
this.day = day;
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;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override
public String toString() {
return "MyDate{" +
"month=" + month +
", day=" + day +
", year=" + year +
'}';
}
//把birthday的比较放在MyDate里
@Override
public int compareTo(MyDate o) {
//如果name相同,比较birthday
//当前对象的year直接使用
int yearMinus=year-o.getYear();
//不是同一年
if(yearMinus !=0){
return yearMinus;
}
//同一年,则比较月
int monthMinus=month-o.getMonth();
//不是同一月
if(monthMinus !=0){
return monthMinus;
}
//同一月
return day-o.getDay();
}
}
3.
下面代码输出什么
public class e5 {
public static void main(String[] args) {
Apple<String, Integer, Double> apple= new Apple<>();
apple.fly(10);//Iteger
apple.fly(new Dog1());//dog1
}
}
class Apple<T,R,M> {//自定义泛型类
public <E> void fly(E e) {//泛型方法
System.out.println(e.getClass().getSimpleName());
}
//public void eat(U u){}错误,U没有声明
public void run(M m) {}
}
class Dog1 {}
4.
定义个泛型类 DAO<T>,在其中定义一个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 单元测试类进行测试。
public class e8 {
public static void main(String[] args) {
}
@Test
public void testList(){
//这里T->User
DAO<User> objectDAO = new DAO<>();
objectDAO.save("1",new User("1",10,"1212"));
objectDAO.save("2",new User("2",10,"1212"));
objectDAO.save("3",new User("3",10,"1212"));
//遍历User
System.out.println(objectDAO.list());
//删除
System.out.println("删除后");
objectDAO.delete("1");
System.out.println(objectDAO);
}
}
class User{
private String id;
private int age;
private String name;
public User(String id, int age, String name) {
this.id = id;
this.age = age;
this.name = name;
}
public String getId() {
return id;
}
public void setId(String 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 + '\'' +
'}';
}
}
class DAO<T>{
private Map<String,T>map=new HashMap<>();
//保存T类型的对象到 Map 成员变量中
public void save(String id,T entity){
map.put(id,entity);
}
// 从 map 中获取 id 对应的对象
public T get(String id){
return map.get(id);
}
//替换 map 中key为id的内容,改为 entity 对象
public void update(String id,T entity){
map.put(id,entity);
}
//返回 map 中存放的所有 T 对象
public List<T> list(){
ArrayList<T> list = new ArrayList<>();
//遍历keyset
Set<String> keyset = map.keySet();
for (String key :keyset) {
list.add(map.get(key));
}
return list;
}
//删除指定 id 对象
public void delete(String id){
map.remove(id);
}
}