创意电子

标题: 深入分析Java集合源码 [打印本页]

作者: Javaer.Yan    时间: 2021-10-2 14:51
标题: 深入分析Java集合源码
1 Java集合概览


                               
登录/注册后可看大图

2 List接口下集合源码分析

2.1 ArrayList

(1)集合体系

                               
登录/注册后可看大图

(2)根本使用
//实例化
ArrayList list = new ArrayList(5);
//添加元素
list.add(1);
list.add(2);
//遍历元素
for (Integer i : list) {
System.out.print(i);
}
for (int i = 0; i < list.size(); i++) {
System.out.print(list.get(i));
}
//删除元素
System.out.println(list.remove(0));
(3)源码剖析
2.2 LinkedList

(1)集合体系

                               
登录/注册后可看大图

(2)根本使用
//实例化
LinkedList linkedList = new LinkedList();
//添加元素
linkedList.add(23);
linkedList.add(44);
linkedList.add(12);
//删除元素,删除的是第一个结点
linkedList.remove();
//修改某个结点对象
linkedList.set(1, 999);
//获取链表的第二个对象
Object o = linkedList.get(1);
//遍历
Iterator iterator = linkedList.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.print(next);
}
for (Object o1 : linkedList) {
System.out.print(o1);
}
for (int i = 0; i < linkedList.size(); i++) {
System.out.print(linkedList.get(i));
}
(3)源码剖析
2.3 Vector

(1)集合体系

                               
登录/注册后可看大图

(2)根本使用
//实例化
Vector vector = new Vector(18);
//添加元素
vector.add(100);
(3)源码剖析
3 Set接口下集合源码分析

3.1 HashSet

(1)集合体系

                               
登录/注册后可看大图

(2)根本使用
HashSet hashSet = new HashSet();
hashSet.add(null);
hashSet.add(null);
hashSet.add("2");
System.out.println("hashSet=" + hashSet);
hashSet.forEach(s -> System.out.println(s));
hashSet.remove(null);
System.out.println(hashSet.contains("2"));
System.out.println(hashSet.contains(null));
(3)源码剖析
3.2 TreeSet

(1)集合体系

                               
登录/注册后可看大图

(2)根本使用
TreeSet treeSet = new TreeSet(new Comparator() {
//排序规则
@Override
public int compare(Object o1, Object o2) {
return ((String) o1).compareTo((String) o2);
}
});
treeSet.add("zs");
treeSet.add("ls");
treeSet.add("ww");
treeSet.add("zl");
(3)源码剖析
4.3 TreeMap

(1)集合体系

                               
登录/注册后可看大图

(2)根本使用
TreeMap treeMap = new TreeMap(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
//按照Key的长度大小排序 相称时只插入一个
return ((String) o2).length() - ((String) o1).length();
}
});
treeMap.put("1", "zs");
treeMap.put("11", "ls");
treeMap.put("12", "ww");
(3)源码剖析
<ul>排序机制:构造方法中传入Comparator接口的匿名内部类
public TreeMap(Comparator




欢迎光临 创意电子 (https://www.wxcydz.cc/) Powered by Discuz! X3.4