Java泛型类编程测试
本文为joshua317原创文章,转载请注明:转载自joshua317博客 https://www.joshua317.com/article/217
package com.joshua317;
import java.util.*;
/**
* 编程要求:
* 1.定义一个泛型类Dao<T>,在其中定义一个map成员变量,map的键为string类型,值为T类型
* (1)public void save(String id, T entity),保存T类型对象到map成员变量中
* (2)public T get(String id),从map中获取id对应的T对象
* (3)public void update(String id, T entity),更新map中key为id的对象,内容为T对象entity
* (4)public List<T> list(),返回map中存放的所有T对象
* (5)public void delete(String id),删除map中指定key为id的对象
* 2.定义一个User类,设置三个私有属性,分别为int id,int age,String name;重写toString方法,显示属性信息
* 3.创建Dao类对象,分别调用Dao类的成员方法来操作User对象
* 4.使用Junit单元类进行单元测试
*/
public class Main {
public static void main(String[] args) {
Dao<User> userDao = new Dao<>();
User user1 = new User(1, 2, "red");
User user2 = new User(2, 3, "yellow");
User user3 = new User(3, 5, "blue");
userDao.save("001", user1);
userDao.save("002", user2);
userDao.save("003", user3);
System.out.println(userDao.get("002"));
System.out.println(userDao.list());
userDao.delete("003");
System.out.println(userDao.list());
user2 = new User(2, 3, "purple");
userDao.update("002",user2);
System.out.println(userDao.list());
}
}
class Dao<T> {
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.replace(id, entity);
}
public List<T> list()
{
ArrayList<T> arrayList = new ArrayList<>();
Set<String> keys = map.keySet();
for (String key: keys) {
arrayList.add(map.get(key));
}
return arrayList;
}
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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", age=" + age +
", name='" + name + '\'' +
'}';
}
}
本文为joshua317原创文章,转载请注明:转载自joshua317博客 https://www.joshua317.com/article/217