好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Java集合教程之Collection实例详解

前言

集合 就是一组数的集合,就像是一个容器,但是我们应该清楚的是集合中存放的都是对象的引用,而不是真正的实体。而我们常说的集合中的对象其实指的就是对象的引用。

我们可以把集合理解为一个小型数据库,用于存放数据,我们对集合的操作也就是数据的增删改查,在 java 中有两个顶层接口 collection 和 map 用于定义和规范集合的相关操作。这篇文章主要说一下集合框架中的 collection 部分。

collection 表示一组对象,这些对象可以是有序也可以是无序的,它提供了不同的子接口满足我们的需求。我们主要看看 list 和 set 。

list 整体的特征就是有序可重复。我们需要研究的是上图中具体的实现类都有什么特性。底层的实现原理是什么,首先来看一看 list 的古老的实现类 vector ,说是古老是因为在 jdk 1.0 的时候就出现了,都走开,我要开始看源码了!这些源码来自于 jdk 1.7。

?

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

public class vector<e>

  extends abstractlist<e>

  implements list<e>, randomaccess, cloneable, java.io.serializable

{

  /**

   * the array buffer into which the components of the vector are

   * stored.

   */

  protected object[] elementdata;

 

  /**

   * the number of valid components in this {@code vector} object.

   */

  protected int elementcount;

 

  /**

   * the amount by which the capacity of the vector is automatically

   * incremented when its size becomes greater than its capacity. if

   * the capacity increment is less than or equal to zero, the capacity

   * of the vector is doubled each time it needs to grow.

   */

  protected int capacityincrement;

 

  public vector() {

   this ( 10 );

  }

 

  // 添加元素

  public synchronized boolean add(e e) {

   modcount++;

   ensurecapacityhelper(elementcount + 1 );

   elementdata[elementcount++] = e;

   return true ;

  }

 

  // 删除元素

  public synchronized e remove( int index) {

   modcount++;

   if (index >= elementcount)

    throw new arrayindexoutofboundsexception(index);

   e oldvalue = elementdata(index);

 

   int nummoved = elementcount - index - 1 ;

   if (nummoved > 0 )

    system.arraycopy(elementdata, index+ 1 , elementdata, index,

         nummoved);

   elementdata[--elementcount] = null ; // let gc do its work

 

   return oldvalue;

  }

 

  // 修改元素

  public synchronized e set( int index, e element) {

   if (index >= elementcount)

    throw new arrayindexoutofboundsexception(index);

 

   e oldvalue = elementdata(index);

   elementdata[index] = element;

   return oldvalue;

  }

  // 查找元素

  public synchronized e get( int index) {

   if (index >= elementcount)

    throw new arrayindexoutofboundsexception(index);

 

   return elementdata(index);

  }

...

就以上源码分析就可以知道关于 vector 的特征。1 底层实现是使用数组来存储数据,所以相应的查找元素和添加元素速度较快,删除和插入元素较慢。2 数组的初始长度为 10 ,当长度不够时,增长量也为 10 使用变量 capacityincrement 来表示。3 方法的声明中都加入了 synchronized 关键字,线程安全的,所以效率相应降低了。 4 没分析出来的再看一遍。

下面开始看 arraylist 的源码。

?

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

public class arraylist<e> extends abstractlist<e>

   implements list<e>, randomaccess, cloneable, java.io.serializable

{

  private static final long serialversionuid = 8683452581122892189l;

 

  /**

   * default initial capacity.

   */

  private static final int default_capacity = 10 ;

 

  /**

   * shared empty array instance used for empty instances.

   */

  private static final object[] empty_elementdata = {};

 

  /**

   * the array buffer into which the elements of the arraylist are stored.

   * default_capacity when the first element is added.

   */

  private transient object[] elementdata;

 

  /**

   * constructs an empty list with an initial capacity of ten.

   */

  public arraylist() {

   super ();

   this .elementdata = empty_elementdata;

  }

 

  // 添加元素

  public boolean add(e e) {

   ensurecapacityinternal(size + 1 ); // increments modcount!!

   elementdata[size++] = e;

   return true ;

  }

 

  // 增加数组的长度

  private void grow( int mincapacity) {

   // overflow-conscious code

   int oldcapacity = elementdata.length;

   int newcapacity = oldcapacity + (oldcapacity >> 1 );

   if (newcapacity - mincapacity < 0 )

    newcapacity = mincapacity;

   if (newcapacity - max_array_size > 0 )

    newcapacity = hugecapacity(mincapacity);

   // mincapacity is usually close to size, so this is a win:

   elementdata = arrays.copyof(elementdata, newcapacity);

  }

...

因为源码和 vector 类似,所以有些就不贴了,但是不耽误我们继续分析 arraylist 。1 底层存储数据使用的还是数组,长度依旧为 10 ,但是进步了,没有在刚开始创建的时候就初始化,而是在添加第一个元素的时候才初始化的。2 方法的声明少了 synchronized 关键字,线程不安全,但性能提高了。3 数组长度不够时,会自动增加为原长度的 1.5 倍。

以上分析也能体现出 vector 和 arraylist 的差别。主要就是想说 vector 已经不用了。使用 arraylist 即可,关于线程安全问题,后面再说。

接着看 linkedlist 的实现,上源码 ~

?

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

public class linkedlist<e>

  extends abstractsequentiallist<e>

  implements list<e>, deque<e>, cloneable, java.io.serializable

{

  transient int size = 0 ;

 

  /**

   * pointer to first node.

   */

  transient node<e> first;

 

  /**

   * pointer to last node.

   */

  transient node<e> last;

 

  /**

   * constructs an empty list.

   */

  public linkedlist() {

  }

 

  // 每一个元素即为一个节点,节点的结构如下(这是一个内部类啊)

  private static class node<e> {

   e item;

   node<e> next;

   node<e> prev;

 

   node(node<e> prev, e element, node<e> next) {

    this .item = element;

    this .next = next;

    this .prev = prev;

   }

  }

 

  // 添加元素

  public boolean add(e e) {

   linklast(e);

   return true ;

  }

 

  void linklast(e e) {

   final node<e> l = last;

   final node<e> newnode = new node<>(l, e, null );

   last = newnode;

   if (l == null )

    first = newnode;

   else

    l.next = newnode;

   size++;

   modcount++;

  }

 

  // 删除某个节点的逻辑

  e unlink(node<e> x) {

   // assert x != null;

   final e element = x.item;

   final node<e> next = x.next;

   final node<e> prev = x.prev;

 

   if (prev == null ) {

    first = next;

   } else {

    prev.next = next;

    x.prev = null ;

   }

 

   if (next == null ) {

    last = prev;

   } else {

    next.prev = prev;

    x.next = null ;

   }

 

   x.item = null ;

   size--;

   modcount++;

   return element;

  }

...

重点就是 linkedlist 的底层实现是双链表。这样就会有以下特性,1 查找元素较慢,但是添加和删除较快。2 占内存,因为每一个节点都要维护两个索引。3 线程不安全 。4 对集合长度没有限制。

以上,list 的几个实现已经分析完成,以后再谈到 vector ,arraylist ,linkedlist 之间的区别应该不会不知所云了吧!还要接着看 collection 的另一个子接口 set 。首先有个大前提,set 中存储的元素是无序不可重复的。然后我们再来看实现类是如何实现的。下面开始 hashset 的表演。

?

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

public class hashset<e>

  extends abstractset<e>

  implements set<e>, cloneable, java.io.serializable

{

  private transient hashmap<e,object> map;

 

  // dummy value to associate with an object in the backing map

  private static final object present = new object();

 

  /**

   * constructs a new, empty set; the backing <tt>hashmap</tt> instance has

   * default initial capacity (16) and load factor (0.75).

   */

  public hashset() {

   map = new hashmap<>();

  }

 

  // 添加元素,其实就是像 map 中添加主键,所以添加的元素不能重复

  public boolean add(e e) {

   return map.put(e, present)== null ;

  }

 

  // 实现 iterable 接口中的 iterator 方法。

  public iterator<e> iterator() {

   return map.keyset().iterator();

  }

...

看了源码才发现,1 原来 hashset 就是对 hashmap 的封装啊,底层实现是基于 hash 表的,回头有必要再好好的介绍一下 hash 相关的知识。2 set 集合中的值,都会以 key 的形式存放在 map 中,所以说 set 中的元素不能重复。3 线程不安全。4 允许存放空值,因为 map 的键允许为空。

今天要说的最后一个实现类终于出现啦,他就是 treeset ,这个实现类中的元素是有序的!注意这里说的有序是指按照一定的规则排序,而我们说 set 集合中的元素无序是因为添加进集合的顺序和输出的顺序不保证一致。treeset 是怎么保证有序我们待会再说,还是一样的套路,是对 treemap 的封装,线程依旧不安全。

?

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

33

34

35

36

37

38

39

40

41

42

public class treeset<e> extends abstractset<e>

  implements navigableset<e>, cloneable, java.io.serializable

{

  /**

   * the backing map.

   */

  private transient navigablemap<e,object> m;

 

  // dummy value to associate with an object in the backing map

  private static final object present = new object();

 

  /**

   * constructs a set backed by the specified navigable map.

   */

  treeset(navigablemap<e,object> m) {

   this .m = m;

  }

 

  /**

   * constructs a new, empty tree set, sorted according to the

   * natural ordering of its elements. all elements inserted into

   * the set must implement the comparable interface.

   */

  public treeset() {

   this ( new treemap<e,object>());

  }

 

  /**

   * constructs a new, empty tree set, sorted according to the specified

   * comparator. all elements inserted into the set must be mutually

   * comparable by the specified comparator

   * if the comparable natural ordering of the elements will be used.

   */

  public treeset(comparator<? super e> comparator) {

   this ( new treemap<>(comparator));

  }

 

  // 添加元素方法

  public boolean add(e e) {

   return m.put(e, present)== null ;

  }

...

我们可以看到 treeset 中构造函数上方的注释,treeset 要保证元素有序,保证有序的思路是在添加元素的时候进行比较。

?

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

33

34

... // 这是 treemap 的 put 方法的节选,为了看到比较的过程。

  public v put(k key, v value) {

  ...

   // split comparator and comparable paths

   comparator<? super k> cpr = comparator;

   if (cpr != null ) {

    do {

     parent = t;

     cmp = cpr.compare(key, t.key);

     if (cmp < 0 )

      t = t.left;

     else if (cmp > 0 )

      t = t.right;

     else

      return t.setvalue(value);

    } while (t != null );

   }

   else {

    if (key == null )

     throw new nullpointerexception();

    comparable<? super k> k = (comparable<? super k>) key;

    do {

     parent = t;

     cmp = k.compareto(t.key);

     if (cmp < 0 )

      t = t.left;

     else if (cmp > 0 )

      t = t.right;

     else

      return t.setvalue(value);

    } while (t != null );

   }

  ...

  }

java 中提供了两种方式,第一种方法,需要我们所添加对象的类实现 comparable 接口,进而实现 compareto 方法,这种方式也叫自然排序,我们并没有传入什么排序规则。这种方式对应 treeset 的空参构造器。而另一种方式就是定制排序,即我们自己定义两个元素的排序规则,在实例化 treeset 的时候传入对应的排序规则即可,对应于 treeset 中带有 comparator 接口的构造器,这里面需要实现 compare 方法 。有点迷糊了是吧,举个例子看看 ~

?

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

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

public class person implements comparable<person>{

 

  public string name;

  public integer age;

 

  public person(string name,integer age) {

   this .name = name;

   this .age = age;

  }

  /* 自定义的比较的逻辑:

   *  首先按照对象的 name 属性排序

   *  其次按照 age 属性排序

   * 方法的返回值为 0 ,大于 0,小于 0 ,分别对应于 相等,大于,和小于

   */

  @override

  public int compareto(person o) {

   int i = this.name.compareto(o.name);

   if(i == 0){

    return this.age.compareto(o.age);

   }else {

    return i;

   }

  }

  @override

  public string tostring() {

   return "[person] name:"+this.name+" age:"+this.age;

  }

}

 

  // 以下是测试代码

  public static void main(string[] args) {

   treeset<person> set = new treeset<>();

   set.add(new person("ajk923",20));

   set.add(new person("bjk923",20));

   set.add(new person("ajk923",21));

   set.add(new person("bjk923",21));

 

   for (person person : set) {

    system.out.println(person.tostring());

   }

   /*

   [person] name:ajk923 age:20

   [person] name:ajk923 age:21

   [person] name:bjk923 age:20

   [person] name:bjk923 age:21

   */

    

   ----以下为定制排序的部分----匿名内部类实现 comparator 接口---- 

   treeset<person> set2 = new treeset<>(new comparator<person>() {

    @override

    public int compare(person o1, person o2) {

     int i = o1.age.compareto(o2.age);

     if(i == 0){

      return o1.name.compareto(o2.name);

     }else {

      return i;

     }

    }

   });

 

   set2.add(new person("ajk923",20));

   set2.add(new person("bjk923",20));

   set2.add(new person("ajk923",21));

   set2.add(new person("bjk923",21));

 

   for (person person : set2) {

    system.out.println(person.tostring());

   }

   /*

    [person] name:ajk923 age:20

    [person] name:bjk923 age:20

    [person] name:ajk923 age:21

    [person] name:bjk923 age:21

    */

  }

上面就是自然排序和定制排序的应用。要说明几点:

1 定制排序和自然排序同时存在的话,优先执行定制排序。可以看看上面的 put 方法的实现 。

2 自然排序对应 comparable 接口,定制排序对应 comparator 接口。

3 string ,包装类,日期类都已经实现了 comparable 接口的 comparato 方法,所以我上面的例子中都偷懒了,没有自己实现具体比较,而是直接调用现成的。

看到这里,也算是对 collection 有了整体的认识,但是这里我并没有说到具体的 api ,我现在日常也用不到几个方法,就放一张 collection 接口的结构图吧,方法也比较简单,看个名字就大概知道什么意思了。

还是要重点说一下 iterator 方法。这个方法定义在 iterable 接口中(collection 继承了 iterable 接口),方法返回的是 iterator 接口对象。iterator 中定义了迭代器的操作规则,而 collection 的实现类中是具体的实现。iterator 接口中定义了 next ,hasnext 和 remove 方法。看一下在arraylist 中是如何实现的吧。

?

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

33

34

35

36

37

38

39

40

41

42

private class itr implements iterator<e> {

   int cursor;  // index of next element to return

   int lastret = - 1 ; // index of last element returned; -1 if no such

   int expectedmodcount = modcount;

 

   public boolean hasnext() {

    return cursor != size;

   }

 

   @suppresswarnings ( "unchecked" )

   public e next() {

    checkforcomodification();

    int i = cursor;

    if (i >= size)

     throw new nosuchelementexception();

    object[] elementdata = arraylist. this .elementdata;

    if (i >= elementdata.length)

     throw new concurrentmodificationexception();

    cursor = i + 1 ;

    return (e) elementdata[lastret = i];

   }

 

   public void remove() {

    if (lastret < 0 )

     throw new illegalstateexception();

    checkforcomodification();

 

    try {

     arraylist. this .remove(lastret);

     cursor = lastret;

     lastret = - 1 ;

     expectedmodcount = modcount;

    } catch (indexoutofboundsexception ex) {

     throw new concurrentmodificationexception();

    }

   }

 

   final void checkforcomodification() {

    if (modcount != expectedmodcount)

     throw new concurrentmodificationexception();

   }

  }

应用起来还是比较简单的,使用一个 while 循环即可。看下面这个例子。

?

1

2

3

4

5

6

7

8

9

10

11

12

13

public static void main(string[] args) {

 

  list<integer> list = new arraylist<>();

  list.add( 1 );

  list.add( 2 );

  list.add( 3 );

 

  iterator<integer> it = list.iterator();

  while (it.hasnext()) {

   integer i = it.next();

   system.out.println(i);

  }

}

不知道你有没有发现,除了 vector 以外,保存集合元素的那个变量都定义为 transient 不管你是数组,node 或是 map ,不由得我又要想一想为什么这样设计?

先看一下 transient 的作用吧!java 的 serialization 提供了一种持久化对象实例的机制。当持久化对象时,可能有一个特殊的对象数据成员,我们不想用 serialization 机制来保存它。为了在一个特定对象的一个域上关闭 serialization,可以在这个域前加上关键字 transient 。当一个对象被序列化的时候,transient 型变量的值不包括在序列化的表示中,非 transient 型的变量是被包括进去的。

那么为什么要这么做呢,好好的标准序列化不用,原因如下:

对于 arraylist 来说,底层实现是数组,而数组的长度和容量不一定相等,可能容量为 10 ,而我们的元素只有 5 。此时序列化的时候就有点浪费资源,序列化和反序列化还是要的,故 arraylist 自己实现了两个方法,分别是 writeobject 和 readobject ,用于序列化和反序列化。

对于 hashset 和  hashmap 来说,底层实现都是依赖于 hash 表,而不同的 jvm 可能算出的 hashcode 值不一致,这样在跨平台的时候就会导致序列化紊乱。故也重写了那两个方法。借用一句似懂非懂的话:

当一个对象的物理表示方法与它的逻辑数据内容有实质性差别时,使用默认序列化形式有 n 种缺陷,所以应该尽可能的根据实际情况重写序列化方法。

对应于 collection ,有一个 collections 工具类,其中提供很多方法,比如说集合的排序,求子集合,最大值,最小值,交换,填充,打乱集合等等,还记得上面说到的实现类中存在线程不安全的情况吧,这个工具类中提供很多对应的 synchronized 的方法。

后记 :不知不觉中扩展了这么多知识点,实话说,肯定还有遗漏的地方,就我现在能想到的依然还有很多,除去 hash 表和 hash 算法这一部分之外,我还没有对底层的数据结构进一步分析,数组,链表,二叉树等等,现在是分析不动了,本文已经很长了。

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对的支持。

原文链接:https://www.cnblogs.com/YJK923/p/9498975.html

查看更多关于Java集合教程之Collection实例详解的详细内容...

  阅读:44次