`

java学习之collection的一些比较

阅读更多
Java集合框架Collection,不管是面试还是开发中用的都是比较多的,其中一些区别也是问的比较多

------HashMap VS HashTable

HashMap 和 HashTable  都是实现的Map<K,V>接口,Map<K,V>就是一个上级接口,它没有继承别的接口,

public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>,Cloneable,Serializable


public class HashTable<K,V> extends Dictionary<K,V> implements Map<K,V>,Cloneable,Serializable


从他们的定义中可以看出他们都是实现的map接口,但是HashMap继承的AbstractMap 而HashTable集成的是Dictionary

api定义上面还有一句话的区别:The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.

综上: HashMap是线程不安全的 HashTable是安全的,且HashMap能允许空值作为key or value

------List<E> VS set<E>

public interface Iterator<T>   T- the type of elements returned by the iterator

public interface Collection<E> extends Iterator<E>   E - the type of elements in this collection


public interface List<E> implements Collection<E>    An ordered collection (also known as a sequence).


public interface Set<E> implements Collection<E>  A collection that contains no duplicate elements and at most one null element.


collection接口集成的Iterator接口,而List和set都是实现了Collection接口

List是一个有序的序列,Set是一个无序的容器,且不能有空元素和不能有重复元素


------ArrayList<E> 和  Vector<E> 和 LinkedList<E>

public ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,  Serializable  (Implements  all optional list operations, and permits all elements, including null and This class is roughly equivalent toVector, except that it is unsynchronized) 


public Vector<E> extends extends AbstractList<E> implements List<E>, RandomAccess, Cloneable,  Serializable

public LinkedList<E> extends AbstractSequentialList<E> implements List<E>,Deque<E>,Cloneable,Serializable


三者都实现了List接口,所以三者都是有序的,

Vector和ArrayList基本是一样的 除了Vector是线程安全的(synchronized)

ArrayList其实是包装了一个数组 Object[],当实例化一个ArrayList时,一个数组也被实例化,当向ArrayList中添加对象是,数组的大小也相应的改变。这样就带来以下有缺点: 快速随即访问 你可以随即访问每个元素而不用考虑性能问题,通过调用get(i)方法来访问下标为i的数组元素。 向其中添加对象速度慢 当你创建数组是并不能确定其容量,所以当改变这个数组时就必须在内存中做很多事情。 操作其中对象的速度慢 当你要想数组中任意两个元素中间添加对象时,数组需要移动所有后面的对象。

LinkedList LinkedList是通过节点直接彼此连接来实现的。每一个节点都包含前一个节点的引用,后一个节点的引用和节点存储的值。当一个新节点插入时,只需要修改其中保持先后关系的节点的引用即可,当删除记录时也一样。这样就带来以下有缺点: 操作其中对象的速度快 只需要改变连接,新的节点可以在内存中的任何地方 不能随即访问 虽然存在get()方法,但是这个方法是通过遍历接点来定位的所以速度慢。

HashSet<E> 实现了set<E>接口

public class HashSet<E> extends AbstractSet<E> implement Set<E>,Serializable,Cloneable (actually a HashMap instance,This class permits the null element)

上面的描述> 实际是一个hashMap实例,这个类允许空元素

虽然Set同List都实现了Collection接口,但是他们的实现方式却大不一样。List基本上都是以Array为基础。但是Set则是在 HashMap的基础上来实现的,这个就是Set和List的根本区别。
HashSet的存储方式是把HashMap中的Key作为Set的对应存储项。看看 HashSet的add(Object obj)方法的实现就可以一目了然了

所以,Set中的元素是不能重复的,如果使用add(Object obj)方法添加已经存在的对象,则会覆盖前面的对象


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics