一、哈希表和有序表的简单使用
- 哈希表:
package com.ittanya.algorithm.HashMap;
import java.util.HashMap;
//哈希表的简单使用
public class HashMapTreeMap {
//(K V)表
public static void main(String[] args) {
HashMap<String,String> map=new HashMap<>();
map.put("Tanya","我是Tanya"); //key value
System.out.println(map.containsKey("Tanya")); //查询
System.out.println(map.containsKey("Tan"));
System.out.println("-------");
System.out.println(map.get("Tanya")); //取值
map.put("Tanya","ta是Tanya"); //更新
System.out.println(map.get("Tanya"));
map.remove("Tanya"); //删除
HashMap<Integer,String> map2=new HashMap<>();
map2.put(1234,"我是1234");
Integer a=1234;
Integer b=1234;
System.out.println(a==b); //false,说明a和b内存地址不一样
System.out.println(a.equals(b)); //true,说明equals比较的是内容
//Integer Double Flo String Char在哈希表内部查询看内容是否相同,内容相同查询结果就相同
System.out.println(map2.containsKey(a));
System.out.println(map2.containsKey(b));
//但是非基础类型在哈希表内部按引用传递,即看的是内存地址(重写hashcode就不一定了)
System.out.println("==========");
Node node1=new Node(1);
Node node2=new Node(1);
HashMap<Node,String> map3=new HashMap<>();
map3.put(node1,"我是node1");
//node1在哈希表里记录的是一个地址,在哈希表内部占用八字节
System.out.println(map3.containsKey(node1));
System.out.println(map3.containsKey(node2));
}
public static class Node{
public int value;
public Node(int V){
value=V;
}
}
}
运行结果:
- 有序表:
package com.ittanya.algorithm.TreeMap;
import java.util.TreeMap;
public class TreeMap1 {
public static void main(String[] args) {
TreeMap<Integer, String> treeMap1 = new TreeMap<>();
treeMap1.put(6, "我是6");
treeMap1.put(2, "我是2");
treeMap1.put(0, "我是0");
treeMap1.put(8, "我是8");
treeMap1.put(1, "我是1");
treeMap1.put(4, "我是4");
System.out.println(treeMap1.containsKey(7));
System.out.println(treeMap1.get(6));
treeMap1.remove(6);
treeMap1.put(6,"他是6");
//TreeMap内部有序排列
System.out.println(treeMap1.firstKey()); //打印最小的key
System.out.println(treeMap1.lastKey()); //打印最大的key
System.out.println(treeMap1.floorKey(6));//打印出<=6的离6最近的key ----6
System.out.println(treeMap1.floorKey(5));//----4
System.out.println(treeMap1.ceilingKey(6));//打印出>=6的离6最近的key -----6
System.out.println(treeMap1.ceilingKey(5)); //-----6
//所有这些方法时间复杂度都是log n级别
//Node node1=new Node(6);
//Node node2=new Node(8);
//TreeMap<Node,String> treeMap2=new TreeMap<>();
//treeMap2.put(node1,"我是node1");
//treeMap2.put(node2,"我是node2");
//报错,因为在TreeMap里key要求 一定要是可以比较的
//需要自己定义为一个可以比较的类型
}
public static class Node{
public int value;
public Node(int V){
value=V;
}
}
}
运行结果: