基本介绍
使用方法
代码演示
package CollectionStudy;import org.junit.jupiter.api.Test;import java.util.*;public class Junit {
public static void main(String[] args) {
}@Testpublic void test() {
DAO<User> dao = new DAO<>();dao.save("001", new User(1, 10, "jack"));dao.save("002", new User(2, 18, "king"));dao.save("003", new User(3, 38, "smith"));List<User> list = dao.list();System.out.println(list);dao.update("003", new User(3, 58, "milan"));System.out.println("===修改后====");list = dao.list();System.out.println("list=" + 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.put(id, entity);}@Testpublic List<T> list() {
ArrayList<T> ts = new ArrayList<>();Collection<T> values = map.values();Iterator<T> iterator = values.iterator();while (iterator.hasNext()) {
ts.add(iterator.next());}return ts;}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;}@Overridepublic String toString() {
return "User{" +"id=" + id +", age=" + age +", name='" + name + '\'' +'}';}
}