List、Set、Map的源码初级分析

来源:互联网 发布:播音软件 编辑:程序博客网 时间:2024/06/18 01:33

 

     Set、Map、List都是利用利用大量的泛型的。

     List和Set都是继承collection接口的。而Map是没有继承任何的接口的。


public interface List<E> extends Collection<E> public interface Set<E> extends Collection<E> {public interface Map<K,V> {


Map源码描述:一个有键值对的对象。一个map不能包含重复的键值对。每一个键最多只能匹配一个值。这个借口可以取代Dictionary类。Dictionary类是一个抽象类而不是一个接口。

原文:

* An object that mapskeys to values.  A map cannot containduplicate keys;

 * each key can map to at most one value.

 *

 * <p>This interface takes the place of the<tt>Dictionary</tt> class, which

 * was a totally abstract class rather than aninterface.

 

List源码描述:一个有序的Collection(作为sequence也是被广为人知),使用List接口的用户能够精确控制在插入的元素的位置。用户可以通过下标来访问和查询里面的元素。List和Set不同,能够插入重复的数据。

原文:

An ordered collection(also known as a<i>sequence</i>).  The user ofthis

 * interface has precise control over where inthe list each element is

 * inserted. The user can access elements by their integer index (position in

 * the list), and search for elements in thelist.<p>

 *

 * Unlike sets, lists typically allow duplicateelements.

 

Set:一个不会包含相同元素的Collection。更加准确的讲,Set是不会包含一对像能够e1.equals(e2)的这样元素,还有至多只有一个空元素。正如它名字所指出的,这个接口模拟数学上的集合的概念。

原文:

A collection thatcontains no duplicate elements.  Moreformally, sets  contain no pair ofelements e1 and e2 such that e1.equals(e2), and at most one null element.  As implied by its name, this interface modelsthe mathematical setabstraction.

 

 

再看下他们实现类ArrayList和HashMap的源码,会发现ArrayList里面

封装的是一个Object数组,HashMap是封装一个内部类的数组

ArrayList的构造方法部分:


public ArrayList(int initialCapacity) {  initialCapacity);………        this.elementData = new Object[initialCapacity];    }

它实例化的时候,默认数组大小为10:


public ArrayList() {        this(10);}


HashMap里面不是利用Object进行封装,而是有一个内部类Entry:

构造方法里面有一句:

table = new Entry[capacity];static final int DEFAULT_INITIAL_CAPACITY = 16;

默认容量是16





0 0
原创粉丝点击