swiftR

java集合继承关系图

upload successful

Vector与ArrayList

Vetor基本用法

1
2
3
Vector vector = new Vector();
vector.add("dog");
System.out.println(vector);

ArrayList与Vector用法类似,都继承自AbstractList

不同的是Vector是一个线程安全的类,如果不需要线程安全,不建议使用,同步是需要线程开销的

1
2
3
4
5
6
public synchronized boolean add(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
return true;
}

ArrayList 是最常见的非线程安全的有序集合,因为内部是数组存储的,所以随机访问效率很高

LinkedList

LinkedList 是使用双向链表数据结构实现的,因此增加和删除效率比较高,而随机访问效率较差。
注意,此实现不同步,如果多个线程同时访问,至少要保持外部同步

基本用法

1
2
3
4
5
6
7
8
LinkedList linkedList = new LinkedList();
linkedList.offer("test");
linkedList.push("test1");

// 获取第一个元素
System.out.println(linkedList.peek());
// 获取第一个元素,并删除此元素
System.out.println(linkedList.poll());

这两个方法都可以向list中添加元素,不同的是
offer为尾部添加

1
2
3
4
5
6
7
8
9
10
11
void linkLast(E e) {
       final Node<E> l = last; //获取尾部节点
       final Node<E> newNode = new Node<>(l, e, null);//new 一个新的节点对象
       last = newNode;
       if (l == null)           //如果尾部节点为null,说明此list中还没有元素,
           first = newNode;
       else //如果尾部节点不为null,将last的下一个元素指向newNode
           l.next = newNode;
size++;
modCount++;
}

push为头部添加

1
2
3
4
5
6
7
8
9
10
11
private void linkFirst(E e) {
final Node<E> f = first;
final Node<E> newNode = new Node<>(null, e, f);
first = newNode;
if (f == null)
last = newNode;
else
f.prev = newNode;
size++;
modCount++;
}

HashSet

HashSet 是一个没有重复元素的集合。是 Set 集合的子类,实际却为 HashMap 的实例

1
2
3
public HashSet() {
map = new HashMap<>();
}

HashSet是无序的,HashSet 默认容量为 16,每次扩充 0.75 倍

1
2
3
4
public HashSet(Collection<? extends E> c) {
map = new HashMap<>(Math.max((int) (c.size()/.75f) + 1, 16));
addAll(c);
}

HashSet通过map的key唯一来保证了hashSet中的值是唯一的

1
2
3
public boolean add(E e) {
return map.put(e, PRESENT)==null;
}

TreeSet

TreeSet 集合实现了自动排序,会把你插入数据进行自动排序。

LinkedHashSet

LinkedHashSet 是按照元素的 hashCode 值来决定元素的存储位置,但同时又使用链表来维护元素的次序,这样使得它看起来像是按照插入顺序保存的

使用与 Vector 类似。

集合排序

排序提供了两种方式:Comparable 和 Comparator

Comparable

需要排序的对象实现Comparable

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
     Stu[] stus =  new Stu[]{new Stu(12,13),new Stu(21,8),
new Stu(9,9),new Stu(24,6)};
Arrays.sort(stus);
System.out.println(Arrays.toString(stus));


}
}

class Stu implements Comparable<Stu>{

private int age;
private int id;

public Stu(int age, int id) {
this.age = age;
this.id = id;
}

@Override
public String toString() {
return "Stu{" +
"age=" + age +
", id=" + id +
'}';
}

@Override
public int compareTo(Stu o) {
return o.age-age;
}
}

Comparator

Comparator 是一个外部比较器,可以通过匿名内部类的方式

1
2
3
4
5
6
Arrays.sort(stus, new Comparator<Stu>() {
@Override
public int compare(Stu o1, Stu o2) {
return o1.age - o2.age;
}
});

Map

map 继承关系图

upload successful

Map接口常用方法

upload successful

HashMap 数据结构