Java学习第四十四天<集合章节作业><泛型引出><泛型说明及细节><泛型应用><自定义泛型><泛型继承和通配><泛型章节作业>

集合章节作业

package chapter17.Homework;
​
import com.sun.deploy.security.MozillaJSSNONEwithRSASignature;
​
import java.util.ArrayList;
​
public class Homework01 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new news("新闻一:新冠确诊病例超千万,数百万印度教徒赴恒河“圣浴”引民众担忧"));
        arrayList.add(new news("新闻二:男子突然想起2个月前钓的鱼还在网兜里,捞起一看赶紧放生"));
        for (int i = arrayList.size()-1; i >=0 ; i--) {
            news n=(news)arrayList.get(i);//拿到getTitle要转型
            System.out.println(progress(n.getTitle()));
        }
​
    }
    //专门写一个方法处理新闻
    public static String progress(String title){
        if (title==null){
            return "";
        }
        if (title.length()>15){
            return title.substring(0,15)+"...";
        }else {
            return title;
        }
    }
}
class news{
    private String title;
    private String text;
​
    public news(String title) {
        this.title = title;
    }
​
    public String getTitle() {
        return title;
    }
​
    @Override
    public String toString() {
        return "news{" +
                "title='" + title + '\'' +
                '}';
    }
}

package chapter17.Homework;
​
import java.util.ArrayList;
​
public class Homework02 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Car("xx",2666));
        arrayList.add(new Car("yy",2686));
        arrayList.add(new Car("zz",26626));
        arrayList.add(new Car("tt",266));
        arrayList.remove(2);
        System.out.println(arrayList.size());
​
        arrayList.addAll(arrayList);
        System.out.println(arrayList.containsAll(arrayList));//查找多个元素是否都存在
        for (Object o :arrayList) {
            System.out.println(o);
        }
        arrayList.removeAll(arrayList);//相当于清空
        System.out.println(arrayList.isEmpty());
    }
}
class Car{
    private String name;
    private int prize;
​
    public Car(String name, int prize) {
        this.name = name;
        this.prize = prize;
    }
​
    @Override
    public String toString() {
        return "Car{" +
                "name='" + name + '\'' +
                ", prize=" + prize +
                '}';
    }
}

package chapter17.Homework;
​
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
​
public class Homework03 {
    public static void main(String[] args) {
        Map m = new HashMap();
        m.put("j",650);
        m.put("t",1200);
        m.put("s",2900);
        System.out.println(m);
        m.replace("j",2600);
​
        Set set = m.entrySet();
        for (Object o :set) {
            Map.Entry m2=(Map.Entry)o;
​
            System.out.println(m2.getKey()+"-"+((int)m2.getValue()+100));//本来是object 要向下转型
        }
​
​
    }
}

package chapter17.Homework;
​
import java.util.TreeSet;
​
public class Homework04 {
    public static void main(String[] args) {
        TreeSet treeSet = new TreeSet();
        treeSet.add(new Person());
        treeSet.add(new Person());
        treeSet.add(new Person());
        treeSet.add(new Person());
        System.out.println(treeSet);
/*
 final int compare(Object k1, Object k2) {
        return comparator==null ? ((Comparable)k1).compareTo((K)k2)  底层会把Person转成Comparable报错 String类实现了Comparable不会报错
            : comparator.compare((K)k1, (K)k2);
    }
 */
    }
}
class Person implements Comparable{
​
    @Override
    public int compareTo(Object o) {
        return 0; //所有加进去的对象都会返回0,不会添加
    }
}

package chapter17.Homework;
​
import java.util.HashSet;
import java.util.Objects;
​
public class Homework05 {
    public static void main(String[] args) {
        HashSet set = new HashSet();
        Persons p1 = new Persons(1001, "AA");
        Persons p2 = new Persons(1002, "BB");
        set.add(p1);
        set.add(p2);
        p1.name="CC";//修改了属性,但哈希值不变,索引不变
        set.remove(p1);//删的是 1001 CC的索引 删不到 p1
        System.out.println(set);
        set.add(new Persons(1001,"CC"));//加的是没删成的位置
        System.out.println(set);
        set.add(new Persons(1001,"AA"));//还是在p1的位置,因为属性不一样,会挂在修改后p1 1001 CC 后面
        System.out.println(set);
    }
}
class Persons{
    private int num;
    public String name;
​
    public Persons(int num, String name) {
        this.num = num;
        this.name = name;
    }
​
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Persons persons = (Persons) o;
        return num == persons.num && Objects.equals(name, persons.name);
    }
​
    @Override
    public int hashCode() {
        return Objects.hash(num, name);
    }
​
    @Override
    public String toString() {
        return "Persons{" +
                "num=" + num +
                ", name='" + name + '\'' +
                '}';
    }
}

泛型引出

package chapter18;
​
import java.util.ArrayList;
//泛型的引出
public class Generic01 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();
        arrayList.add(new Dog("xx",10));
        arrayList.add(new Dog("yy",1));
        arrayList.add(new Dog("zz",5));
       // arrayList.add(new Cat("tt",6));
​
        for (Object o :arrayList) {//传统方法 需转型效率低
            Dog d=(Dog) o;//若不小心添了一个猫类会异常
            System.out.println(d.getName()+"-"+d.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 int getAge() {
        return 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 int getAge() {
        return age;
    }
}

package chapter18;
​
import java.util.ArrayList;
​
public class Generic02 {
    public static void main(String[] args) {
        ArrayList arrayList = new ArrayList();//只能存放Dog2 遍历时候可直接取Dog2类 不是object类
        arrayList.add(new Dog2("xx",10));
        arrayList.add(new Dog2("yy",1));
        arrayList.add(new Dog2("zz",5));
       //  arrayList.add(new Cat2("tt",6));
​
        for (Dog2 o :arrayList) {//少了转换
            System.out.println(o.getName()+"-"+o.getAge());
        }
    }
}
class Dog2{
    private String name;
    private int age;
​
    public Dog2(String name, int age) {
        this.name = name;
        this.age = age;
    }
​
    public String getName() {
        return name;
    }
​
    public int getAge() {
        return age;
    }
}
class Cat2{
    private String name;
    private int age;
​
    public Cat2(String name, int age) {
        this.name = name;
        this.age = age;
    }
​
    public String getName() {
        return name;
    }
​
    public int getAge() {
        return age;
    }
}

泛型说明及细节

package chapter18;
​
public class Generic03 {
    public static void main(String[] args) {
        Person xx = new Person<>("xx"); // Person类中所有E>String
        xx.show();//class java.lang.String
        Person yy = new Person<>(100);
        yy.show();//class java.lang.Integer
​
    }
}
class Person{
    E s;//定义Person对象时候指定的数据类型,编译期间知道是什么类型
​
    public Person(E s) {//可作为参数类型
        this.s = s;
    }
    public E f(){//可作为返回类型
        return  s;
    }
    public void show(){
        System.out.println(s.getClass());
    }
}

package chapter18;
​
import java.util.ArrayList;
​
public class GenericDetail {
    public static void main(String[] args) {
        Mig aMig = new Mig(new A());//E 为A类型
        Mig aMig1 = new Mig<>(new B());//可传A的子类 右边<>可简写 左边<>不写默认object类
        aMig.show();//A 运行类型
        aMig1.show();//B
​
​
    }
}
class A{}
class B extends A{}
class Mig{
    E s;
​
    public Mig(E s) {
        this.s = s;
    }
    public void show(){
        System.out.println(s.getClass());
    }
}

泛型应用

package chapter18;
​
import java.util.*;
​
public class GenericExercise {
    public static void main(String[] args) {
        HashMap hashMap = new HashMap<>();
        hashMap.put("xx",new Student("xx",55));
        hashMap.put("yy",new Student("yy",56));
        hashMap.put("zz",new Student("zz",57));
        Set> entries = hashMap.entrySet();
        Iterator> iterator = entries.iterator();
        while (iterator.hasNext()) {
            Map.Entry next =  iterator.next();
            System.out.println(next.getKey()+"-"+next.getValue());
        }
        HashSet set = new HashSet<>();
        set.add(new Student("jj",12));
        set.add(new Student("jg",13));
        set.add(new Student("jk",14));
        for (Student student :set) {
            System.out.println(student);
        }
​
​
    }
}
class Student{
    private String name;
    private int age;
​
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }
​
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

package chapter18;
​
import java.util.ArrayList;
import java.util.Comparator;
​
public class GenericExercise02 {
    public static void main(String[] args) {
        Employee xx = new Employee("xx", 25, new Employee.MyDate(2008, 12, 24));
        Employee yy = new Employee("kk", 25, new Employee.MyDate(2005, 16, 21));
        Employee kk = new Employee("kk", 25, new Employee.MyDate(2055, 16, 21));
        Employee zz = new Employee("zz", 25, new Employee.MyDate(2018, 13, 2));
        ArrayList employees = new ArrayList<>();
        employees.add(xx);
        employees.add(yy);
        employees.add(kk);
        employees.add(zz);
        System.out.println(employees);
        System.out.println("排序后");
        employees.sort(new Comparator() {
            @Override
            public int compare(Employee o1, Employee o2) {
                  if (!(o1 instanceof Employee&&o2 instanceof Employee)){//加验证
                      System.out.println("类型不对");
                      return 0;
                  }
                  int i=o1.getName().compareTo(o2.getName());
                  if (i!=0){
                      return i;
                  }else {
                      return o1.birthday.compareTo(o2.birthday);
                  }
​
​
            };
        });
        System.out.println(employees);
​
​
    }
}
class Employee{
    private String name;
    private double sal;
    MyDate birthday;
    static class MyDate implements Comparable{//对年月日的比较进行封装 泛型对应下边
   private int year;
   private int month;
   private int date;
​
        public MyDate(int year, int month, int date) {
            this.year = year;
            this.month = month;
            this.date = date;
        }
​
        public int getYear() {
            return year;
        }
​
        public int getMonth() {
            return month;
        }
​
        public int getDate() {
            return date;
        }
​
        @Override
        public String toString() {
            return "MyDate{" +
                    "year=" + year +
                    ", month=" + month +
                    ", date=" + date +
                    '}';
        }
​
        @Override
        public int compareTo(MyDate o) {//对年月日的比较进行封装 //泛型显示MyDate
            //如果名字相同,比较生日
            int j=year-o.getYear();
            if (j!=0){
                return j;
            }
            int k=month-o.getMonth();
            if (k != 0) {
                return k;
            }
            int g=date-o.getDate();
            return g;
        }
    }
​
    public Employee(String name, double sal, MyDate birthday) {
        this.name = name;
        this.sal = sal;
        this.birthday = birthday;
    }
​
    public String getName() {
        return name;
    }
​
    @Override
    public String toString() {
        return "\nEmployee{" +
                "name='" + name + '\'' +
                ", sal=" + sal +
                ", birthday=" + birthday +
                '}';
    }
}

自定义泛型

自定义泛型类

package chapter18;
​
public class CustomGeneric {
    public static void main(String[] args) {
​
    }
}
class Tiger{//自定义泛型类
    R r;
    M m;
    T t;
​
    public Tiger(R r, M m, T t) {
        this.r = r;
        this.m = m;
        this.t = t;
    }
​
    public void setR(R r) {
        this.r = r;
    }
​
    public void setM(M m) {
        this.m = m;
    }
​
    public void setT(T t) {
        this.t = t;
    }
    //T[] ts=new T[8];泛型数组不允许初始化 因为类型不同开辟空间未知
    //static R r2; 静态成员/属性方法与类一起加载,但对象还没创建,泛型还没指定,所以静态成员不能用泛型
​
}

自定义泛型接口

package chapter18;
​
public class CustomInterfaceGeneric {
    public static void main(String[] args) {
​
    }
}
interface Usb{
    //U name="ss";接口成员都是静态性质
    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 Usb{//继承接口,指定泛型
​
}
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 Usb{//直接实现也能匹配类型,不写默认object
​
    @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) {
​
    }
}

自定义泛型方法

package chapter18;
​
public class CustomMethodGeneric {
    public static void main(String[] args) {
        Car car = new Car();
        car.fly("xx",100);//调用方法时,传参确定类型
    }
}
class Car{
    public void run(){//普通方法
​
    }
    public void fly(T t,R r){//泛型方法
        System.out.println(t.getClass());
        System.out.println(r.getClass());//自动装箱变引用类型
    }
    /*public void swim(R r){  错误,不是泛型方法,且类名中没有指定R泛型
​
    }*/
}

泛型继承和通配

 

泛型章节作业

package chapter18;
​
import org.junit.jupiter.api.Test;
​
import java.util.*;
​
public class Homework01 {
    public static void main(String[] args) {
​
    }
    @Test//alt+enter
    public void test(){
        DAO dao = new DAO<>();
        dao.save("001",new User(1,10,"jj"));
        dao.save("002",new User(2,18,"jk"));
        dao.save("003",new User(3,38,"jl"));
        List list = dao.list();
        System.out.println(list);
        dao.update("003",new User(3,58,"op"));
        dao.delete("001");
        list=dao.list();//重新获取
        System.out.println(list);
        System.out.println(dao.get("002"));
    }
}
class DAO{
    private Map map=new HashMap<>();  //K-String V-T类对象
​
    public void save(String id,T entity){
        map.put(id, entity);
    }
    public T get(String id){
        return map.get(id);
    }
    public void update(String id,T entity){
     map.put(id, entity);
    }
    public List list(){//遍历map[k-v] 将所有value(entity)封装到Arraylist返回
       List list = new ArrayList<>();
        Set keySet = map.keySet();
        for (String s :keySet) {
            list.add(get(s));//map.get(s)
        }
         return list;
    }
    public void delete(String id){
      map.remove(id);
    }
​
}
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 int getAge() {
        return age;
    }
​
    public String getName() {
        return name;
    }
​
    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }
}

你可能感兴趣的:(java,学习,开发语言)