泛型的使用练习题

    xiaoxiao2022-07-02  122

    题目要求:

    Dao泛型类:

    public 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){ if (map.containsKey(id)){ map.put(id,entity); } } //返回map中存放的所有的T对象 public List<T> list(){ //错误的: //Collection<T> values = map.values(); //return (List<T>) values; //正确的; List<T> list = new ArrayList<>(); Collection<T> values = map.values(); for (T t : values){ list.add(t); } return list; } //删除指定id对象 public void delete(String id){ map.remove(id); } }

     User 类:

    public class User { private int id; private int age; private String name; public User() { } public User(int id, int age, String name) { this.id = id; this.age = age; this.name = name; } @Override public String toString() { return "User{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + '}'; } @Override public int hashCode() { return super.hashCode(); } @Override public boolean equals(Object obj) { return super.equals(obj); } 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; } }

    测试类:

    public class DaoTest { public static void main(String[] args) { Dao<User> dao = new Dao<>(); dao.save("1001",new User(101,34,"周杰伦")); dao.save("1002",new User(102,35,"琨林")); dao.save("1003",new User(103,64,"蔡依林")); dao.update("1003",new User(104,30,"反就")); List<User> list = dao.list(); list.forEach(System.out::println); } }

     

     

    最新回复(0)