5 changed files with 101 additions and 0 deletions
@ -0,0 +1,31 @@ |
|||
package w8; |
|||
|
|||
public class Pair<K, V> { |
|||
private K key; |
|||
private V value; |
|||
|
|||
public Pair(K key, V value) { |
|||
this.key = key; |
|||
this.value = value; |
|||
} |
|||
|
|||
public Pair<V, K> swap() { |
|||
return new Pair<>(this.value, this.key); |
|||
} |
|||
|
|||
public K getKey() { |
|||
return key; |
|||
} |
|||
|
|||
public void setKey(K key) { |
|||
this.key = key; |
|||
} |
|||
|
|||
public V getValue() { |
|||
return value; |
|||
} |
|||
|
|||
public void setValue(V value) { |
|||
this.value = value; |
|||
} |
|||
} |
|||
@ -0,0 +1,32 @@ |
|||
package w8; |
|||
|
|||
import java.util.HashMap; |
|||
import java.util.Map; |
|||
|
|||
public class Cache<K, V> { |
|||
private final Map<K, V> cacheMap; |
|||
|
|||
public Cache() { |
|||
cacheMap = new HashMap<>(); |
|||
} |
|||
|
|||
public void put(K key, V value) { |
|||
cacheMap.put(key, value); |
|||
} |
|||
|
|||
public V get(K key) { |
|||
return cacheMap.get(key); |
|||
} |
|||
|
|||
public void remove(K key) { |
|||
cacheMap.remove(key); |
|||
} |
|||
|
|||
public void clear() { |
|||
cacheMap.clear(); |
|||
} |
|||
|
|||
public int size() { |
|||
return cacheMap.size(); |
|||
} |
|||
} |
|||
@ -0,0 +1,22 @@ |
|||
package w9; |
|||
|
|||
import java.util.Date; |
|||
public class Article { |
|||
private String title; |
|||
private String content; |
|||
private String author; |
|||
private Date publishDate; |
|||
|
|||
public Article() {} |
|||
public Article(String title, String content, String author, Date publishDate) { |
|||
this.title = title; |
|||
this.content = content; |
|||
this.author = author; |
|||
this.publishDate = publishDate; |
|||
} |
|||
|
|||
public String getAuthor() { return author; } |
|||
public void setAuthor(String author) { this.author = author; } |
|||
public Date getPublishDate() { return publishDate; } |
|||
public void setPublishDate(Date publishDate) { this.publishDate = publishDate; } |
|||
} |
|||
@ -0,0 +1,15 @@ |
|||
package w9; |
|||
|
|||
import java.util.ArrayList; |
|||
import java.util.List; |
|||
public class HistoryCommand { |
|||
private List<String> commandList = new ArrayList<>(); |
|||
|
|||
|
|||
public void addCommand(String cmd) { |
|||
commandList.add(cmd); |
|||
} |
|||
public List<String> getHistory() { |
|||
return new ArrayList<>(commandList); |
|||
} |
|||
} |
|||
@ -0,0 +1 @@ |
|||
直接返回的List<Article>是引用传递,外部代码可直接修改集合内 Article 对象或增删元素,存在数据安全风险。其一,外部修改 Article 的标题、作者等字段,会直接篡改内存中原始数据,引发数据不一致;其二,外部可随意新增、删除集合元素,破坏数据完整性;其三,多线程场景下,共享集合无同步机制,易出现并发异常、脏数据。需返回集合副本或不可变集合,避免外部直接操作原始数据。 |
|||
Loading…
Reference in new issue