泛型Practices

 

1: 

定义个泛型类 DAO<T>,在其中定义一个 Map 成员变量,Map 的键 为 String 类型,值为 T 类型。 
 
分别创建以下方法: public void save(String id,T entity): 保存 T 类型的对象到 Map 成员 变量中 

public T get(String id):从 map 中获取 id 对应的对象

public void update(String id,T entity):替换 map 中 key 为 id 的内容, 改为 entity 对象

public List<T> list():返回 map 中存放的所有 T 对象

public void delete(String id):删除指定 id 对象

定义一个 User 类:
该类包含:
private 成员变量(int 类型) id,age;( String 类型)name。
定义一个测试类:
创建 DAO 类的对象, 分别调用其 save、get、update、list、delete 方 法来操作 User 对象, 使用 Junit 单元测试类进行测试。

 

Dao类

package June.JuneEight.JuneEightAfternoon;

import java.util.*;

public class JuneEightAfternoonDao<T> {
    private HashMap<String,T> hashMap = new HashMap<String, T>();

    public void save(String id,T entity){
        hashMap.put(id,entity);
    }

    public T getT(String id){
        return hashMap.get(id);
    }

    public void update(String id, T entity){


        if(hashMap.containsKey(id)){
            hashMap.put(id,entity);
        }

    }

    public List<T>list(){
//        Collection listCollection = hashMap.values();
//
//        List<T> list = new ArrayList<>();
//        list.add(listCollection);

        ArrayList<T> list = new ArrayList();
        Collection <T> collection = hashMap.values();
        for (T e:collection
             ) {
            list.add(e);
        }
        return list;
    }

    public void deletes(String id){
        hashMap.remove(id);
    }
}
Dao类

 

 

User类

package June.JuneEight.JuneEightAfternoon;

import java.util.Objects;

public class JuneEightAfternoonUser<T> {

    private int id;
    private int age;
    private String name;

    public JuneEightAfternoonUser(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 "JuneEightAfternoonUser{" +
                "id=" + id +
                ", age=" + age +
                ", name='" + name + '\'' +
                '}';
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        JuneEightAfternoonUser<?> user = (JuneEightAfternoonUser<?>) o;
        return id == user.id &&
                age == user.age &&
                Objects.equals(name, user.name);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, age, name);
    }
}
User类

切记: Map使用的自定义类要重写equals()方法

 

测试类

    @Test
    public void TestOne(){
        JuneEightAfternoonDao<JuneEightAfternoonUser> dao = new JuneEightAfternoonDao<JuneEightAfternoonUser>();
        JuneEightAfternoonUser userOne = new JuneEightAfternoonUser(1,18,"老王");
        dao.save("1001",userOne);
        System.out.println(dao.getT("1001"));

        dao.update("1002",new JuneEightAfternoonUser(1,46,"隔壁老王"));

        System.out.println(dao.list());
        dao.save("1002",new JuneEightAfternoonUser(2,46,"隔壁老王"));
        dao.save("1003",new JuneEightAfternoonUser(3,23,"隔壁小姐姐"));
        System.out.println(dao.list());
        dao.deletes("1003");
        System.out.println(dao.list());
    }
测试类

 

 

 

 

 

2: 

定义一个 Employee 类, 
该类包含:private 成员变量 name,age,birthday,其中 birthday 为 MyDate 类的 对象; 
并为每一个属性定义 getter, setter 方法; 
并重写 toString 方法输出 name, age, birthday 
 
MyDate 类包含: private 成员变量 month,day,year;并为每一个属性定义 getter, setter 方法; 
 
创建该类的 5 个对象,并把这些对象放入 TreeSet 集合中(TreeSet 需使用泛型 来定义), 分别按以下两种方式对集合中的元素进行排序,并遍历输出: 
 
1). 使 Employee 继承 Comparable 接口,并按 name 排序 
2). 创建 TreeSet 时传入 Comparator 对象,按生日日期的先后排序。

Employee类

package June.JuneNine.JuneNineForenoon;

import org.junit.Test;


public class JuneNineForenoonEmployee<T> implements Comparable<JuneNineForenoonEmployee> {
    private String name;
    private int age;
    private JuneNineForenoonMyDate birthday;

    public JuneNineForenoonEmployee(String name, int age, JuneNineForenoonMyDate birthday) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
    }

    // 泛型使用后的方法

    @Override
    public int compareTo(JuneNineForenoonEmployee juneNineForenoonEmployee) {
        return this.name.compareTo(juneNineForenoonEmployee.name);
    }



    /*
    // 按照姓名排序 ---- 为指明泛型时的使用
    @Override
    public int compareTo(Object object){
        if(object instanceof JuneNineForenoonEmployee){
            JuneNineForenoonEmployee obj = (JuneNineForenoonEmployee) object;
            return this.name.compareTo(obj.name);
        }
        throw  new RuntimeException("输入的有误");
    }

     */

    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;
    }

    public JuneNineForenoonMyDate getBirthday() {
        return birthday;
    }

    public void setBirthday(JuneNineForenoonMyDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "JuneNineForenoonEmployee{" +
                "name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }



}
Employee

 

 

package June.JuneNine.JuneNineForenoon;

public class JuneNineForenoonMyDate implements Comparable<JuneNineForenoonMyDate> {
    private int month;
    private int day;
    private int year;

    public JuneNineForenoonMyDate(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 int compareTo(JuneNineForenoonMyDate myDat) {
                    // 比较年
            int minusYear = this.getYear()- myDat.getYear();
            if(minusYear != 0 ){
                return minusYear;
            }

            //比较月

            int minusMonth = this.getMonth() - myDat.getMonth();
            if(minusMonth != 0){
                return minusMonth;
            }

            // 比较日
            return this.getDay()- myDat.getDay();
    }


    // 未使用泛型分方法
//    @Override
//    public int compareTo(Object object){
//        if(object instanceof  JuneNineForenoonMyDate){
//            JuneNineForenoonMyDate obj = (JuneNineForenoonMyDate) object;
//
//            // 比较年
//            int minusYear = this.getYear()- obj.getYear();
//            if(minusYear != 0 ){
//                return minusYear;
//            }
//
//            //比较月
//
//            int minusMonth = this.getMonth() - obj.getMonth();
//            if(minusMonth != 0){
//                return minusMonth;
//            }
//
//            // 比较日
//            int minusDay = this.getDay()- obj.getDay();
//            if(minusDay != 0){
//                return minusDay;
//            }
//        }
//        throw  new RuntimeException("输入有误");
//    }
}
MyDate类

 

 

Test类

package June.JuneNine.JuneNineForenoon;

import org.junit.Test;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class JuneNineForenoonPracticeTestOne {


    @Test
    public void TestOne(){
        TreeSet<JuneNineForenoonEmployee>set = new TreeSet<>();
        set.add(new JuneNineForenoonEmployee("老王",12,new JuneNineForenoonMyDate(1,23,3004)));
        set.add(new JuneNineForenoonEmployee("老张",18,new JuneNineForenoonMyDate(5,25,1995)));
        Iterator<JuneNineForenoonEmployee> iterator = set.iterator();
        while (iterator.hasNext()){
            JuneNineForenoonEmployee employee = iterator.next();
            System.out.println(employee);
        }
    }



    @Test
    public void TestTwo(){

    TreeSet<JuneNineForenoonEmployee> treeSet = new TreeSet<>(new Comparator<JuneNineForenoonEmployee>() {
        @Override
        public int compare(JuneNineForenoonEmployee e1, JuneNineForenoonEmployee e2) {
            JuneNineForenoonMyDate b1 = e1.getBirthday();
            JuneNineForenoonMyDate b2 = e2.getBirthday();
            return b1.compareTo(b2);
        }
    });

    treeSet.add(new JuneNineForenoonEmployee("老王头",18,new JuneNineForenoonMyDate(3,23,1869)));
    treeSet.add(new JuneNineForenoonEmployee("隔壁小姐姐",26,new JuneNineForenoonMyDate(6,23,1996)));
        for (JuneNineForenoonEmployee employee : treeSet) {
            System.out.println(employee);
        }
    }

}
测试类

 

 

3: 写出使用Iterator 和 增强for 循环遍历List<String>的代码,使用上泛型

    @Test
    public void TestTwo() {

        ArrayList<String> list = new ArrayList<>();
        Iterator<String> iterator = list.iterator();
        while (iterator.hasNext()){
            iterator.next();
        }

        for (String  str:list
             ) {
            System.out.println(str);
        }
    }
写出使用Iterator 和 增强for 循环遍历List的代码,使用上泛型

 

 

4:    如何遍历Map的key集,value集,key-value集,使用上泛型

    @Test
    public void TestOne() {
        HashMap<String, Integer> hashMap = new HashMap<>();
        hashMap.put("老王", 23);
        hashMap.put("隔壁老王", 43);
        hashMap.put("老张头", 57);
        hashMap.put("老李", 18);

        // 取key
        Set<String> str = hashMap.keySet();

        for (String string : str
        ) {
            System.out.println(string);
        }

        // 取value
        Collection<Integer> va = hashMap.values();
        Iterator<Integer> integerIterator = va.iterator();
        while (integerIterator.hasNext()) {
            System.out.println(integerIterator.next());
        }
    }
如何遍历Map的key集,value集,key-value集,使用上泛型

 

5: 提供一个方法,用于遍历获取HashMap<String,String>中的所有value,并存放在List中返回。考虑上集合中泛型的使用。

    @Test
    public List<String>  getValue(HashMap<String,String> hashMap){
        ArrayList<String> arrayList = new ArrayList<>();
        Collection<String> collection = hashMap.values();
//        Iterator<String> stringIterator = collection.iterator();
        for (String s: collection
             ) {
            arrayList.add(s);
        }
        return  arrayList;
    }
提供一个方法,用于遍历获取HashMap<String,String>中的所有value,并存放在List中返回。考虑上集合中泛型的使用。

 

 

 

6:  Map接口中的常用方法有哪些

添加: put(key, value)

删除: remove(key)

改;put(key,value)

查 get(key)

匹配 :containsKey(key)

 

posted @ 2020-06-08 18:12  可爱的红领巾  阅读(350)  评论(0编辑  收藏  举报