public static void main(String[] args) {
/**
* 线程安全
*/
Hashtable<String, String> hashtable = new Hashtable<>();
hashtable.put("abc", "afc");
System.out.println(hashtable.get("abc"));
/**
* 底层为数组+(链表+红黑树:采用尾插法),线程不安全
*/
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("abc", "afc");
System.out.println(hashMap.get("abc"));
/**
* 和HashMap结构基本一样,且1.8以后,锁的粒度很低,即tab[index],锁定数组中的节点,(猜想:如果为链表,则为链表头节点,如果为红黑树,则锁定的是红黑树的根节点),线程安全
*/
ConcurrentHashMap<String, String> concurrentHashMap = new ConcurrentHashMap<>();
concurrentHashMap.put("abc", "afc");
System.out.println(concurrentHashMap.get("abc"));
/**
* LinkedBlockingQueue,实现了BlockingQueue,采用可重入锁保证线程安全
*/
LinkedBlockingQueue<String> linkedBlockingQueue = new LinkedBlockingQueue<>();
linkedBlockingQueue.add("abc");
System.out.println("linkedBlockingQueue.peek()" + linkedBlockingQueue.peek()); // linkedBlockingQueue.peek()abc
System.out.println("linkedBlockingQueue.poll()" + linkedBlockingQueue.poll()); // linkedBlockingQueue.poll()abc
System.out.println("linkedBlockingQueue.offer(\"bbb\")" + linkedBlockingQueue.offer("bbb")); // linkedBlockingQueue.offer("bbb")true
System.out.println(linkedBlockingQueue.size()); // 1
System.out.println("linkedBlockingQueue.poll()" + linkedBlockingQueue.poll()); // linkedBlockingQueue.poll()bbb
/**
* 实现了List和Deque(双向队列),数据结构是一个双向链表 ,线程不安全
*/
LinkedList<String> linkedList = new LinkedList<>();
linkedList.add("aa");
linkedList.get(0);
System.out.println(linkedList.iterator().next());
/**
* 数据结构是数组,线程不安全
*/
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("a");
arrayList.add(0, "b");
System.out.println("arrayList.get(0)" + arrayList.get(0)); // arrayList.get(0)b
/**
*HashMap<E,Object> map;线程不安全
*/
HashSet<String> hashSet = new HashSet<>();
hashSet.add("abc");
System.out.println(hashSet.iterator().next());
/**
* 底层是一个NavigableMap<E,Object> m,主要是实现了NavigableSet,这个NavigableSet又实现了SorterdMap,所以值是有序的,且为自然排序
*/
TreeSet<String> treeSet = new TreeSet<>();
/**
* 也可以自定义比较器
*/
// Comparator<String> comparator= Comparator.comparing(...);
// TreeSet<String> treeSetCompare = new TreeSet<comparator>();
treeSet.add("abc");
treeSet.addAll(arrayList);
System.out.println("treeSet.iterator().next()" + treeSet.iterator().next()); // treeSet.iterator().next()a
/**
* 底层为数组,线程安全
*/
Vector<String> vector = new Vector<String>();
vector.add("aaa");
System.out.println(vector.get(0));
/**
* stack 线程安全,实现了Vector接口,底层是一个数组
*/
Stack<String> stack = new Stack<>();
stack.push("aaa");
// stack.pop() 出栈栈顶元素,并取值
System.out.println("stack.pop()" + stack.pop()); // stack.pop()aaa
stack.push("bbb");
// stack.peek() 只是取出当前数组中的值,不出栈
System.out.println("stack.peek()" + stack.peek()); // stack.peek()bbb
stack.add("ccc");
// stack.add(0,"ddd");在栈指定索引处添加值
stack.add(0, "ddd");
System.out.println("stack.iterator().next()" + stack.iterator().next()); // stack.iterator().next()ddd
}
java集合
最新推荐文章于 2024-10-16 10:13:45 发布