Android/Java Map/Set/List....

来源:互联网 发布:网络直播的优缺点 编辑:程序博客网 时间:2024/06/11 07:23

根据不同博客整理,还请原作者见谅...

本人一般不原创博客,怕有误人子弟之嫌,此篇只是整理之果,仅供参考....


     在Android开发中我们经常需要对数据进行分类和操作,对于轻量级的数据存储我们可能不需要动用SQLite或效率以及类库不完善的XML,由于 SharedPreferences不具备数据枚举方法,如果仅仅是一个String或Int数组可以通过一个标记分割设计外,我们还是主要来看看 Android或者说Java提供的基础数据类型辅助类ArrayList LinkedList Set HashMap的介绍。


     在Java中提供了Collection和Map接口。其中List和Set继承了Collection接口;同时用Vector、ArrayList、 LinkedList三个类实现List接口,HashSet、TreeSet实现Set接口。直接有HashTable、HashMap、 TreeMap实现Map接口。如下图:


Collection
├List
│├LinkedList
│├ArrayList
│└Vector
│ └Stack
└Set
   |-HashSet
   |-TreeSet


Map

├Hashtable
├HashMap
└WeakHashMap

1: Collection接口

     public class  Collections extends Object

     Collections contains static methods which operate on Collection classes.


    Collection是最基本的集合接口,一个Collection代表一组 Object,即Collection的元素(Elements)。一些Collection允许相同的元素而另一些不行。一些能排序而另一些不行。 Java SDK不提供直接继承自Collection的类,Java SDK提供的类都是继承自Collection的“子接口”如List和Set。所有实现Collection接口的类都必须提供两个标准的构造函数:无参数的构造函数用于创建一个空的Collection,有一个 Collection参数的构造函数用于创建一个新的Collection,这个新的Collection与传入的Collection有相同的元素。后 一个构造函数允许用户复制一个Collection。如何遍历Collection中的每一个元素?不论Collection的实际类型如何,它都支持一个iterator()的方法,该方法返回一个迭代子,使用该迭代子即可逐一访问Collection中每一个元素。典型的用法如下:


Iterator it = collection.iterator(); // 获得一个迭代子

while(it.hasNext()) {

Object obj = it.next(); // 得到下一个元素

}

或者:

for (Iterator it =collection.iterator(); it.hasNext();) {    Object obj = it.next(); // 得到下一个元素}  

由Collection接口派生的两个接口是List和Set。


1.1:  List接口

       public interface List implements Collection<E>

List is a collection which maintains an ordering for its elements. Every element in the List has an index. Each element can thus be accessed by its index, with the first index being zero. Normally, Lists allow duplicate elements, as compared to Sets, where elements have to be unique.

       List是有序的Collection,使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的数组。和下面要提到的Set不同,List允许有相同的元素。除了具有Collection接口必备的iterator()方法外,List还提供一个listIterator()方法,返回一个 ListIterator接口,和标准的Iterator接口相比,ListIterator多了一些add()之类的方法,允许添加,删除,设定元素, 还能向前或向后遍历。
实现List接口的常用类有LinkedList,ArrayList,Vector和Stack。

  List总结
        1. 所有的List中只能容纳单个不同类型的对象组成的表,而不是Key-Value键值对。例如:[ tom,1,c ];
        2. 所有的List中可以有相同的元素,例如Vector中可以有 [ tom,koo,too,koo ];
        3. 所有的List中可以有null元素,例如[ tom,null,1 ];
        4. 基于Array的List(Vector,ArrayList)适合查询,而LinkedList(链表)适合添加,删除操作。
  虽然Set同List都实现了Collection接口,但是他们的实现方式却大不一样。List基本上都是以Array为基础。但是Set则是在 HashMap的基础上来实现的,这个就是Set和List的根本区别。


1.1.1:LinkedList类

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

 LinkedList is an implementation of List, backed by a doubly-linked list. All optional operations including adding, removing, and         replacing elements are supported.

         All elements are permitted, including null.

         This class is primarily useful if you need queue-like behavior. It may also be useful as a list if you expect your lists to contain zero or one element, but still require the ability to scale to slightly larger numbers of elements. In general, though, you should probably use ArrayList if you don't need the queue-like behavior.


LinkedList实现了List接口,允许null元素。此外LinkedList提供额外的get,remove,insert方法在 LinkedList的首部或尾部。这些操作使LinkedList可被用作堆栈(stack),队列(queue)或双向队列(deque)。注意LinkedList没有同步方法。如果多个线程同时访问一个List,则必须自己实现访问同步。一种解决方法是在创建List时构造一个同步的List:
List list = Collections.synchronizedList(new LinkedList(...));


LinkedList:不同于前面两种List,它不是基于Array的,作为链表数据结构方式,所以不受Array性能的限制。当对 LinkedList做添加,删除动作的时候只要更改nextNode的相关信息就可以实现了所以它适合于进行频繁进行插入和删除操作。这就是 LinkedList的优势,当然对于元素的位置获取等方面就逊色很多。


1.1.2:ArrayList类

         public class ArrayList extends AbstractList<E> implements Serializable Cloneable RandomAccess

ArrayList is an implementation of List, backed by an array. All optional operations including adding, removing, and replacing elements are supported.

All elements are permitted, including null.

This class is a good choice as your default List implementation. Vector synchronizes all operations, but not necessarily in a way that's meaningful to your application: synchronizing each call to get, for example, is not equivalent to synchronizing the list and iterating over it (which is probably what you intended). CopyOnWriteArrayList is intended for the special case of very high concurrency, frequent traversals, and very rare mutations.

ArrayList实现了可变大小的数组。它允许所有元素,包括null。ArrayList没有同步。
size,isEmpty,get,set方法运行时间为常数。但是add方法开销为分摊的常数,添加n个元素需要O(n)的时间。其他的方法运行时间为线性。
每个ArrayList实例都有一个容量(Capacity),即用于存储元素的数组的大小。这个容量可随着不断添加新元素而自动增加,但是增长算法并 没有定义。当需要插入大量元素时,在插入前可以调用ensureCapacity方法来增加ArrayList的容量以提高插入效率。和LinkedList一样,ArrayList也是非同步的(unsynchronized)。


  ArrayList:同Vector一样是一个基于Array的,但是不同的是ArrayList不是同步的。所以在性能上要比Vector优越一些。 Android123提示大家适用于顺序性的查找

1.1.3:Vector类

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


Vector is an implementation of List, backed by an array and synchronized. All optional operations including adding, removing, and replacing elements are supported.

All elements are permitted, including null.

This class is equivalent to ArrayList with synchronized operations. This has a performance cost, and the synchronization is not necessarily meaningful to your application: synchronizing each call to get, for example, is not equivalent to synchronizing on the list and iterating over it (which is probably what you intended). If you do need very highly concurrent access, you should also consider CopyOnWriteArrayList.


Vector非常类似ArrayList,但是Vector是同步的。由Vector创建的Iterator,虽然和ArrayList创建的 Iterator是同一接口,但是,因为Vector是同步的,当一个Iterator被创建而且正在被使用,另一个线程改变了Vector的状态(例 如,添加或删除了一些元素),这时调用Iterator的方法时将抛出ConcurrentModificationException,因此必须捕获该 异常。


Vector基于Array的List,性能也就不可能超越Array,并且Vector是“sychronized”的,这个也是Vector和 ArrayList的唯一的区别。

1.1.3.1:Stack 类

public class Stack extends Vector<E>

Stack is a Last-In/First-Out(LIFO) data structure which represents a stack of objects. It enables users to pop to and push from the stack, including null objects. There is no limit to the size of the stack.
Stack继承自Vector,实现一个后进先出的堆栈。Stack提供5个额外的方法使得 Vector得以被当作堆栈使用。基本的push和pop方法,还有peek方法得到栈顶的元素,empty方法测试堆栈是否为空,search方法检测 一个元素在堆栈中的位置。Stack刚创建后是空栈。

        

1.2:Set接口

Set是一种不包含重复的元素的Collection,即任意的两个元素e1和e2都有e1.equals(e2)=false,Set最多有一个null元素。
很明显,Set的构造函数有一个约束条件,传入的Collection参数不能包含重复的元素。
请注意:必须小心操作可变对象(Mutable Object)。如果一个Set中的可变元素改变了自身状态导致Object.equals(Object)=true将导致一些问题。

Set总结: 

1. Set实现的基础是Map(HashMap); 

2. Set中的元素是不能重复的,如果使用add(Object obj)方法添加已经存在的对象,则会覆盖前面的对象,不能包含两个元素e1、e2(e1.equals(e2))。

3。Set是数学中定义的集合,所以元素无序, 且不能重复添加。java程序中Set集合用的不多,


  HashSet:HashSet的存储方式是把HashMap中的Key作为Set的对应存储项,HashMap的key是不能有重复的。HashSet 能快速定位一个元素,但是放到HashSet中的对象需要实现hashCode()方法0。HashSet:就像是把HashMap中value去掉,说白了就是只有一个key的HashMap集合。
    TreeSet:将放入其中的元素按序存放,这就要求你放入其中的对象是可排序的。TreeSet不同于HashSet的根本是TreeSet是有序的。它是通过SortedMap来实现的。


1.2.1: HashSet

public class HashSet extends AbstractSet<E> implements Serializable Cloneable Set<E>

HashSet is an implementation of a Set. All optional operations (adding and removing) are supported. The elements can be any objects.


1.2.2:TreeSet

public class TreeSet extends AbstractSet<E> implements Serializable Cloneable NavigableSet<E>

TreeSet is an implementation of SortedSet. All optional operations (adding and removing) are supported. The elements can be any objects which are comparable to each other either using their natural order or a specified Comparator.


2:Map接口

public interface Map

Map is a data structure consisting of a set of keys and values in which each key is mapped to a single value. The class of the objects used as keys is declared when the Map is declared, as is the class of the corresponding values.

Map provides helper methods to iterate through all of the keys contained in it, as well as various methods to access and update the key/value pairs.

请注意,Map没有继承Collection接口,Map提供key到value的映射。一个Map中不能包含相同的key,每个key只能映射一个 value。Map接口提供3种集合的视图,Map的内容可以被当作一组key集合,一组value集合,或者一组key-value映射。


Map是一种把键对象(key)和值对象(value)进行关联的容器,关键字key是唯一不重复的。Map是一个有序的集合,所以查询起来速度很快
Map有两种比较常用的实现: HashTable、HashMap和TreeMap。

    TreeMap则是对键按序存放,因此它有一些扩展的方法,比如firstKey(),lastKey()等。

    HashMap和Hashtable的区别。 HashMap允许空(null)键(key)或值(value),由于非线程安全,效率上可能高于Hashtable。 Hashtable不允许空(null)键(key)或值(value)。

2.1:Hashtable类

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

Hashtable is a synchronized implementation of Map. All optional operations are supported.

Neither keys nor values can be null. (Use HashMap or LinkedHashMap if you need null keys or values.)


Hashtable继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value。
添加数据使用put(key, value),取出数据使用get(key),这两个基本操作的时间开销为常数。
Hashtable 通过initial capacity和load factor两个参数调整性能。通常缺省的load factor 0.75较好地实现了时间和空间的 均衡。增大load factor可以节省空间但相应的查找时间将增大,这会影响像get和put这样的操作。使用Hashtable的简单示例如下,将1,2,3放到Hashtable中,他们的key分别是”one”,”two”,”three”:
Hashtable numbers = new Hashtable();
numbers.put(“one”, new Integer(1));
numbers.put(“two”, new Integer(2));
numbers.put(“three”, new Integer(3));
要取出一个数,比如2,用相应的key:
Integer n = (Integer)numbers.get(“two”);
System.out.println(“two = ” + n);
由于作为key的对象将通过计算其散列函数来确定与之对应的value的位置,因此任何作为key的对象都必须实现hashCode和equals方 法。hashCode和equals方法继承自根类Object,如果你用自定义的类当作key的话,要相当小心,按照散列函数的定义,如果两个对象相 同,即obj1.equals(obj2)=true,则它们的hashCode必须相同,但如果两个对象不同,则它们的hashCode不一定不同,如 果两个不同对象的hashCode相同,这种现象称为冲突,冲突会导致操作哈希表的时间开销增大,所以尽量定义好的hashCode()方法,能加快哈希 表的操作。如果相同的对象有不同的hashCode,对哈希表的操作会出现意想不到的结果(期待的get方法返回null),要避免这种问题,只需要牢记一条:要同时复写equals方法和hashCode方法,而不要只写其中一个。Hashtable是同步的。


2.2:HashMap类

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

HashMap is an implementation of Map. All optional operations are supported.

All elements are permitted as keys or values, including null.

Note that the iteration order for HashMap is non-deterministic. If you want deterministic iteration, use LinkedHashMap.

Note: the implementation of HashMap is not synchronized. If one thread of several threads accessing an instance modifies the map structurally, access to the map needs to be synchronized. A structural modification is an operation that adds or removes an entry. Changes in the value of an entry are not structural changes.

The Iterator created by calling the iterator method may throw a ConcurrentModificationException if the map is structurally changed while an iterator is used to iterate over the elements. Only the remove method that is provided by the iterator allows for removal of elements during iteration. It is not possible to guarantee that this mechanism works in all cases of unsynchronized concurrent modification. It should only be used for debugging purposes.


HashMap和Hashtable类似,不同之处在于HashMap是非同步的,并且允许null,即null value和null key。,但 是将HashMap视为Collection时(values()方法可返回Collection),其迭代子操作时间开销和HashMap的容量成比 例。因此,如果迭代操作的性能相当重要的话,不要将HashMap的初始化容量设得过高,或者load factor过低。


  HashMap也用到了哈希码的算法,以便快速查找一个键,

2.3:WeakHashMap类

public class WeakHashMap extends AbstractMap<K, V> implements Map<K, V>

WeakHashMap is an implementation of Map with keys which are WeakReferences. A key/value mapping is removed when the key is no longer referenced. All optional operations (adding and removing) are supported. Keys and values can be any objects. Note that the garbage collector acts similar to a second thread on this collection, possibly removing keys.
WeakHashMap是一种改进的HashMap,它对key实行“弱引用”,如果一个key不再被外部所引用,那么该key可以被GC回收。


        总结
如果涉及到堆栈,队列等操作,应该考虑用List,对于需要快速插入,删除元素,应该使用LinkedList,如果需要快速随机访问元素,应该使用ArrayList。
如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高,如果多个线程可能同时操作一个类,应该使用同步的类。
要特别注意对哈希表的操作,作为key的对象要正确复写equals和hashCode方法。
尽量返回接口而非实际的类型,如返回List而非ArrayList,这样如果以后需要将ArrayList换成LinkedList时,客户端代码不用改变。这就是针对抽象编程。


    同步性
Vector 是同步的。这个类中的一些方法保证了Vector中的对象是线程安全的。而ArrayList则是异步的,因此ArrayList中的对象并不是线程安全 的。因为同步的要求会影响执行的效率,所以如果你不需要线程安全的集合那么使用ArrayList是一个很好的选择,这样可以避免由于同步带来的不必要的 性能开销。
    数据增长
从内部实现机制来讲ArrayList和Vector都是使用数组(Array)来控制集合中的对象。当你向这两种类 型中增加元素的时候,如果元素的数目超出了内部数组目前的长度它们都需要扩展内部数组的长度,Vector缺省情况下自动增长原来一倍的数组长度, ArrayList是原来的50%,所以最后你获得的这个集合所占的空间总是比你实际需要的要大。所以如果你要在集合中保存大量的数据那么使用 Vector有一些优势,因为你可以通过设置集合的初始化大小来避免不必要的资源开销。
    使用模式
在ArrayList和Vector中, 从一个指定的位置(通过索引)查找数据或是在集合的末尾增加、移除一个元素所花费的时间是一样的,这个时间我们用O(1)表示。但是,如果在集合的其他位 置增加或移除元素那么花费的时间会呈线形增长:O(n-i),其中n代表集合中元素的个数,i代表元素增加或移除元素的索引位置。为什么会这样呢?以为在 进行上述操作的时候集合中第i和第i个元素之后的所有元素都要执行位移的操作。这一切意味着什么呢?
        这意味着,你只是查找特定位置的元素或只在集 合的末端增加、移除元素,那么使用Vector或ArrayList都可以。如果是其他操作,你最好选择其他的集合操作类。比如,LinkList集合类 在增加或移除集合中任何位置的元素所花费的时间都是一样的?O(1),但它在索引一个元素的使用缺比较慢-O(i),其中i是索引的位置.使用 ArrayList也很容易,因为你可以简单的使用索引来代替创建iterator对象的操作。LinkList也会为每个插入的元素创建对象,所有你要 明白它也会带来额外的开销。
        最后,在《Practical Java》一书中Peter Haggar建议使用一个简单的数组(Array)来代 替Vector或ArrayList。尤其是对于执行效率要求高的程序更应如此。因为使用数组(Array)避免了同步、额外的方法调用和不必要的重新分 配空间的操作。

原创粉丝点击