package com.generic;
import org.junit.jupiter.api.Test;
import java.util.*;
/*
定义个泛型类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类型) nam
创建DAO类的对象,分别调用其save、get、update、list、delete方法来操作User对象,使用Junit单元测试类进行测试。
*/
@SuppressWarnings({"all"})
public class Exercise {
public static void main(String[] args) {
}
@Test
public void testList(){
DAO<User> dao = new DAO<>();
dao.save("001",new User(1,18,"tom"));
dao.save("002",new User(2,20,"jack"));
dao.save("003",new User(3,19,"jam"));
List<User> list = dao.list();
System.out.println(list);
dao.update("003",new User(3,22,"pual"));
System.out.println("===修改后===");
System.out.println(list);
dao.delete("003");
System.out.println("===删除后===");
System.out.println(list);
}
}
class DAO<T>{
private Map<String,T> map = new HashMap<>();
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);
}
//返回 map中存放的所有T对象
//遍历map [k-v],将map的所有value(T entity),封装到ArrayList返回即可
public List<T> list(){
//创建ArrayList
List<T> list = new ArrayList<>();
//遍历map
Set<String> keySet = map.keySet();
for (String k : keySet) {
list.add(get(k));
}
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 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 + '\'' +
'}';
}
}
标签:map,String,id,练习,list,JUnit,void,泛型,public
From: https://www.cnblogs.com/Q1u-ovo/p/17347882.html