1. Collection和Set的区别?
Set是内容不重复的Collection,继承了Collection接口
2. Map是不是Collection?
Map是一种映射关系(两个集合间的对应关系),不是Collection
3. TreeMap和HashMap的区别?
TreeMap是通过树来实现的映射,是有序的,不允许null;HashMap是通过hash表来实现的映射,无序,允许null
4. HashMap vs HashTable
HashTable是线程安全的,通过synchronized关键字实现同步,不允许为null;HashMap是线程不安全的,允许为null
5. 实现Key-Value的LRU缓存
import java.util.Iterator;import java.util.LinkedHashMap;import java.util.stream.Collectors;import java.util.stream.StreamSupport;public class LRUCache<K, V> implements Iterable<K>{private final int max = 3;private final LinkedHashMap<K, V> cache = new LinkedHashMap<>(max);public void cache(K key, V value) {if (cache.containsKey(key)) {cache.remove(key);} else if (cache.size() >= max) {Iterator<K> iterator = cache.keySet().iterator();iterator.next();iterator.remove();}cache.put(key, value);}@Overridepublic Iterator<K> iterator() {return cache.keySet().iterator();}public static void main(String[] args) {LRUCache<String, Integer> cache = new LRUCache<>();cache.cache("A", 1);System.out.println("leave <-" + StreamSupport.stream(cache.spliterator(), false).collect(Collectors.joining("<-")));cache.cache("B", 2);System.out.println("leave <-" + StreamSupport.stream(cache.spliterator(), false).collect(Collectors.joining("<-")));cache.cache("C", 3);System.out.println("leave <-" + StreamSupport.stream(cache.spliterator(), false).collect(Collectors.joining("<-")));cache.cache("D", 4);System.out.println("leave <-" + StreamSupport.stream(cache.spliterator(), false).collect(Collectors.joining("<-")));cache.cache("C", 10);System.out.println("leave <-" + StreamSupport.stream(cache.spliterator(), false).collect(Collectors.joining("<-")));}}
