哈希表
哈希表的操作时间复杂度都是O(1),与数据量无关,但常数时间很大。
基础类型:按值传递,内存里占用的是这个变量的实际大小。
非基础类型:按引用传递,内存占用的是这个变量内存地址的大小。
HashMap
有key、有value
常见用法
增(put)、删(remove)、改(put)和查(get)。
remove是按key去删除元素的
HashMap<String, Integer> hashMap1 = new HashMap<>();
map.put("a", 1);
map.put("b", 2);
map.remove("a");
map.remove("b");
map.get("a");
map.get("b");
如何删除HashMap中指定值的元素
注意:不能直接在迭代器中去删除元素,这样会破坏迭代器的结构。正确的方式是现将要删除的元素存入List中,然后再遍历List去删除元素。
Code如下:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Map_Test {
public static class Node {
public int value;
public Node next;
public Node(int val) {
value = val;
}
}
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 1);
map.put("c", 2);
map.put("d", 1);
map.put("e", 2);
map.put("f", 1);
List<String> removeKeys = new ArrayList<>();
for (Map.Entry<String, Integer> entry: map.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
if (value.equals(1)) {
removeKeys.add(key);
}
}
for (String key: removeKeys) {
map.remove(key);
}
}
}
HashSet
有key、无value
各种用法
增加 add;
删除 remove;
对比查找 contains;
清空集合 clear();
获取长度 size();
有序表
与哈希表的区别:有序表把key按顺序组织,而哈希表完全不组织。放入有序表中的元素,若不是基础类型,必须提供比较器,才能让key在内部有序组织。
TreeMap
TreeMap<Integer, String> treeMap1 = new TreeMap<>();
treeMap1.put(7, "我是7");
treeMap1.put(5, "我是5");
treeMap1.put(4, "我是4");
treeMap1.put(3, "我是3");
treeMap1.put(9, "我是9");
treeMap1.put(2, "我是2");
System.out.println(treeMap1.containsKey(5)); //true
System.out.println(treeMap1.get(5)); //我是5
System.out.println(treeMap1.firstKey() + ", 我最小");
System.out.println(treeMap1.lastKey() + ", 我最大");
System.out.println(treeMap1.floorKey(8) + ", 在表中所有<=8的数中,我离8最近");
System.out.println(treeMap1.ceilingKey(8) + ", 在表中所有>=8的数中,我离8最近");
System.out.println(treeMap1.floorKey(7) + ", 在表中所有<=7的数中,我离7最近");
System.out.println(treeMap1.ceilingKey(7) + ", 在表中所有>=7的数中,我离7最近");
treeMap1.remove(5);
TreeSet
import java.util.*;
import java.util.TreeSet;
public class Map_Test {
public static class Node {
public int value;
public Node next;
public Node(int val) {
value = val;
}
}
// 非基础类型必须提供比较器
public static class NodeComparator implements Comparator<Node> {
@Override
public int compare(Node o1, Node o2) {
return o1.value - o2.value;
}
}
public static void main(String[] args) {
Node nodeA = new Node(5);
Node nodeB = new Node(3);
Node nodeC = new Node(7);
TreeSet treeSet = new TreeSet<>(new NodeComparator());
// 以下的代码没问题,因为提供了Node类型的比较器
try {
treeSet.add(nodeA);
treeSet.add(nodeB);
treeSet.add(nodeC);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}