谈Java数据结构之前先聊聊C的数据结构
常见的数据结构有线性表、链表、队列、堆栈、树、图等
像压缩可以选择用树
像数据库索引可以选择用B+树
Java代码实例
Stack的代码
package com.fuping.liuqu.demo.test; import java.util.Stack; public class DataStructureDemo { public static void main(String[] args) { Stack<String> stack = new Stack<>(); stack.add("first"); String pop = stack.pop(); System.out.println(pop); System.out.println(stack.size()); stack.add("two"); String peek = stack.peek(); System.out.println(peek); System.out.println(stack.size()); stack.push("23"); stack.push("24"); stack.push("25"); stack.addElement("26"); stack.insertElementAt("34", 5); peek = stack.peek(); System.out.println(peek); System.out.println(stack.size()); pop = stack.pop(); System.out.println(pop); System.out.println(stack.size()); } }代码运行的结果
two 1 two 2 push:23 26 7 26 6 Process finished with exit code 0线性表
package com.fuping.liuqu.demo.test; import java.util.ArrayList; import java.util.List; public class DataStructureDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(16); list.add("first"); System.out.println(list); } }链表
package com.fuping.liuqu.demo.test; import java.util.LinkedList; public class DataStructureDemo { public static void main(String[] args) { LinkedList<String> linkedList = new LinkedList<>(); linkedList.add("twe"); linkedList.add("first"); System.out.println(linkedList); } }结果
[twe, first] Process finished with exit code 0队列
package com.fuping.liuqu.demo.test; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; public class DataStructureDemo { public static void main(String[] args) { Queue<String> queue = new ConcurrentLinkedQueue<>(); queue.add("first"); queue.add("two"); String element = queue.element(); System.out.println(element); } }结果
first Process finished with exit code 0 package com.fuping.liuqu.demo.test; import java.util.NavigableMap; import java.util.TreeMap; public class DataStructureDemo { public static void main(String[] args) { // 导航函数Map NavigableMap<String, String> navigableMap = new TreeMap<>(); // key是弱键 WeakHashMap<String, String> weakHashMap = new WeakHashMap<>(); } }BlockingQueue、BlockingDeque LinkedBlockingQueue 无界队列,注意OOM,注意最大线程数的陷阱, Executors.newFixedThreadPool()的底层队列,Executors.newSingleThreadExecutor()的底层队列 ArrayBlockingQueue 有界队列,注意OOM DelayQueue 延迟队列,Redis底层实现的队列 DelayedWorkQueue JDK内部实现队列,Executors.newScheduledThreadPool()底层实现队列 PriorityQueue 优先级队列,可自定义排序,默认自然排序 PriorityBlockingQueue 优先级阻塞队列 ConcurrentSkipListMap 跳跃表Map,查询快 ConcurrentSkipListSet 跳跃表Set ConcurrentLinkedMap 同步的链表Map CopyOnWriteArrayList 写入时复制数组List,类似于Linux底层的Copy-On-Write技术,例如配置、黑名单、物流地址等变化非常少的数据,这是一种无锁的实现。可以帮我们实现程序更高的并发。可参考学习:https://baijiahao.baidu.com/s?id=1636057331750965212&wfr=spider&for=pc CopyOnWriteArraySet 写入时复制数组Set TransferQueue 抢占式队列,分公平式与非公平式,默认非公平 SychronousQueue 同步队列,Executors.newCachedThreadPool()的底层实现队列 TreeMap 有序Map TreeSet 有序Set