一、常用集合类实现
public class TreeSetTest { public static void main(String[] args) { TreeSet<Item> setById = new TreeSet<Item>(); // 1.Exception if Item not implement Comparable interface // Exception in thread "main" java.lang.ClassCastException: Item cannot be cast to java.lang.Comparable setById.add(new Item(1, "level 9")); setById.add(new Item(2, "level 2")); setById.add(new Item(3, "level 5")); System.out.println(setById); // 2.Use comparator TreeSet<Item> setByDesc = new TreeSet<Item>( new Comparator<Item>() { @Override public int compare(Item o1, Item o2) { return o1.desc.compareTo(o2.desc); } }); setByDesc.addAll(setById); System.out.println(setByDesc); } } class Item implements Comparable<Item> { int id; String desc; Item(int id, String desc) { this.id = id; this.desc = desc; } @Override public int compareTo(Item o) { return id - o.id; } @Override public String toString() { return "Item [id=" + id + ", desc=" + desc + "]"; } }
public class LRUTest { public static void main(String[] args) { Map<Item, Integer> lruMap = new LinkedHashMap<Item, Integer>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Map.Entry<Item, Integer> eldest) { return size() > 3; } }; lruMap.put(new Item(1, "111"), 1); lruMap.put(new Item(2, "222"), 2); lruMap.put(new Item(3, "333"), 3); lruMap.put(new Item(4, "444"), 4); System.out.println(lruMap); lruMap.put(new Item(5, "555"), 5); System.out.println(lruMap); } }