package class03; import java.util.HashMap; import java.util.HashSet; import java.util.TreeMap; /** * 哈希表和有序表 */ public class HashMapAndSortedMap { public static class Node { public int value; public Node(int v) { value = v; } } public static class Zuo { public int value; public Zuo(int v) { value = v; } } public static void main(String[] args) { int a = 512213654; int b = 512213654; System.out.println(a == b); HashMap<Integer, String> test = new HashMap<>(); test.put(a, "a的值"); String s = test.get(b); System.out.println("s = " + s); System.out.println(test.containsKey(a));//true。按值传递,512213654 == 512213654,所以true。 Zuo z1 = new Zuo(1); Zuo z2 = new Zuo(2); HashMap<Zuo, String> test2 = new HashMap<>(); test2.put(z1, "这是z1"); System.out.println(test2.containsKey(z2));//false。因为是按引用传递,z2就是没进来过,所以是false。 //UnSortedMap HashMap<Integer, String> map = new HashMap<>(); map.put(1, "这是1"); map.put(2, "这是2"); map.put(3, "这是3"); map.put(4, "这是4"); map.put(5, "这是5"); map.put(6, "这是6"); System.out.println(map.containsKey(1)); System.out.println(map.containsKey(10)); System.out.println(map.get(4)); System.out.println(map.get(10)); map.put(4, "他是4"); System.out.println(map.get(4)); map.remove(4); System.out.println(map.get(4)); //只有key,没有value HashSet<String> set = new HashSet<>(); set.add("abc"); set.contains("abc"); set.remove("abc"); //哈希表的增、删、改、查,在使用时,都是O(1)。 System.out.println("================================"); Integer c = 1000; Integer d = 1000; System.out.println(c.equals(d)); System.out.println(c == d); Integer e = 127; Integer f = 127; System.out.println(e.equals(f)); System.out.println(e == f); Integer g = 128; Integer h = 128; System.out.println(g.equals(h)); System.out.println(g == h); //常量池,[-128, 127] HashMap<Node, String> map2 = new HashMap<>(); Node node1 = new Node(1); Node node2 = node1; map2.put(node1, "这是node1"); map2.put(node2, "这是node1"); System.out.println(map2.size());//1。因为按引用传递。 System.out.println("================================"); //TreeMap //时间复杂度:O(logN) System.out.println("有序表测试开始:"); TreeMap<Integer, String> treeMap = new TreeMap<>(); treeMap.put(3, "这是3"); treeMap.put(2, "这是2"); treeMap.put(5, "这是5"); treeMap.put(9, "这是9"); treeMap.put(1, "这是1"); treeMap.put(6, "这是6"); System.out.println(treeMap.containsKey(1)); System.out.println(treeMap.containsKey(10)); System.out.println(treeMap.get(6)); System.out.println(treeMap.get(10)); treeMap.put(6, "他是6"); System.out.println(treeMap.get(6)); treeMap.remove(6); System.out.println(treeMap.get(6)); System.out.println("TreeMap比HashMap多的功能:"); System.out.println(treeMap.firstKey()); System.out.println(treeMap.lastKey()); System.out.println(treeMap.floorKey(6));//<=6,离6最近的key System.out.println(treeMap.ceilingKey(6));//>=6,离6最近的key } }
标签:map,哈希,treeMap,System,put,有序,println,out From: https://www.cnblogs.com/TheFloorIsNotTooHot/p/16859546.html