Android笔记六.List+Set+Map

来源:互联网 发布:梦幻西游2网络错误 编辑:程序博客网 时间:2024/05/16 06:57
List+Set+Map
转载请表明出处:http://blog.csdn.net/u012637501(嵌入式_小J的天空)
一、Java定义集合接口
Java Collections Framework是Java提供的对集合进行定义,操作,和管理的包含一组接口(即数据容器),类的体系结构。
  Java集合框架的基本接口/类层次结构:
  java.util.Collection [I]-集合
  +--java.util.List [I]   -线性集(无序,可重复)
  +--java.util.ArrayList [C]---不同步,类似动态数组
  +--java.util.LinkedList [C]--链表(访问有序)
  +--java.util.Vector [C]------同步,类似动态数组
  +--java.util.Stack [C]--------栈
  +--java.util.Set [I]---规则集(不可重复)
  +--java.util.HashSet [C]---哈希集
  +--java.util.SortedSet [I]--有序集(自动排序)
  +--java.util.TreeSet [C]---树集
  java.util.Map [I]--图(键值对形式存储)
  +--java.util.SortedMap [I]
  +--java.util.TreeMap [C]
  +--java.util.Hashtable [C]---同步
  +--java.util.HashMap [C]----不同步
  +--java.util.LinkedHashMap [C]
  +--java.util.WeakHashMap [C]
  [I]:接口
  [C]:类
1. Collection接口
  Collection是最基本的集合接口,一个Collection代表一组Object(对象)的集合,这些Object被称作Collection的元素。 
  所有实现Collection接口的类都必须提供两个标准的构造函数:无参数的构造函数用于创建一个空的Collection,有一个 Collection参数的构造函数用于创建一个新的Collection,这 个新的Collection与传入的Collection有相同的元素。后一个构造函数允许用户复制一个Collection。
  如何遍历Collection中的每一个元素?不论Collection的实际类型如何,它都支持一个iterator()的方法,该方法返回一个迭代子使用该迭代子即可逐一访问Collection中每一个元素。典型的用法如下:
  Iterator it = Collection.iterator(); // 获得一个迭代子     while(it.hasNext())     {           Object obj = it.next(); // 得到下一个元素     }
  根据用途的不同,Collection又划分为List与Set。
2.List接口
  List继承自Collection接口。List是有序的Collection使用此接口能够精确的控制每个元素插入的位置。用户能够使用索引(元素在List中的位置,类似于数组下标)来访问List中的元素,这类似于Java的数组
  跟Set集合不同的是List允许有重复元素。对于满足e1.equals(e2)条件的e1与e2对象元素,可以同时存在于List集合中。当然,也有List的实现类不允许重复元素的存在。除了具有Collection接口必备的iterator()方法外,List还提供一个listIterator()方法,返回一个 ListIterator接口,和标准的Iterator接口相比,ListIterator多了一些add()之类的方法,允许添加,删除,设定元素, 还能向前或向后遍历。
  实现List接口的常用类有LinkedList,ArrayList,Vector和Stack。
(1)LinkedList类
  LinkedList实现了List接口,允许null元素。此外LinkedList提供额外的get,remove,insert方法在 LinkedList的首部或尾部。这些操作使LinkedList可被用作堆栈(stack),队列(queue)或双向队列(deque)
  注意LinkedList没有同步方法。如果多个线程同时访问一个List,则必须自己实现访问同步。一种解决方法是在创建List时构造一个同步的List:
  List list = Collections.synchronizedList(new LinkedList(...));
(2)ArrayList类
  ArrayList实现了可变大小的数组。它允许所有元素,包括null。ArrayList没有同步
  size,isEmpty,get,set方法运行时间为常数。但是add方法开销为分摊的常数,添加n个元素需要O(n)的时间。其他的方法运行时间为线性。
  每个ArrayList实例都有一个容量(Capacity),即用于存储元素的数组的大小。这个容量可随着不断添加新元素而自动增加,但是增长算法并 没有定义。当需要插入大量元素时,在插入前可以调用ensureCapacity方法来增加ArrayList的容量以提高插入效率。
  和LinkedList一样,ArrayList也是非同步的(unsynchronized)。
(3)Vector类
  Vector非常类似ArrayList,但是Vector是同步的。由Vector创建的Iterator,虽然和ArrayList创建的 Iterator是同一接口,但是,因为Vector是同步的,当一个Iterator被创建而且正在被使用,另一个线程改变了Vector的状态(例如,添加或删除了一些元素),这时调用Iterator的方法时将抛出ConcurrentModificationException,因此必须捕获该异常。
(4)Stack 类
  Stack继承自Vector,实现一个后进先出的堆栈。Stack提供5个额外的方法使得Vector得以被当作堆栈使用。基本的push和pop方 法,还有peek方法得到栈顶的元素,empty方法测试堆栈是否为空,search方法检测一个元素在堆栈中的位置。Stack刚创建后是空栈。
3.Set接口
  Set继承自Collection接口。Set是一种不能包含有重复元素的集合,即对于满足e1.equals(e2)条件的e1与e2对象元素,不能同时存在于同一个Set集合里,换句话说,Set集合里任意两个元素e1和e2都满足e1.equals(e2)==false条件,Set最多有一个 null元素。
  因为Set的这个制约,在使用Set集合的时候,应该注意:
  1,为Set集合里的元素的实现类实现一个有效的equals(Object)方法。
  2,对Set的构造函数,传入的Collection参数不能包含重复的元素。
  请注意:必须小心操作可变对象(Mutable Object)。如果一个Set中的可变元素改变了自身状态导致Object.equals(Object)=true将导致一些问题。
4.Map接口
  Map没有继承Collection接口。也就是说Map和Collection是2种不同的集合
   Collection可以看作是(value)的集合,而Map可以看作是(key,value)的集合----图
  Map接口由Map的内容提供3种类型的集合视图,一组key集合,一组value集合,或者一组key-value映射关系的集合。
(1)Hashtable类
  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)HashMap类
  HashMap和Hashtable类似,不同之处在于HashMap是非同步的,并且允许null,即null value和null key。,但是将HashMap视为Collection时(values()方法可返回Collection),其迭代子操作时间开销和HashMap 的容量成比例。因此,如果迭代操作的性能相当重要的话,不要将HashMap的初始化容量设得过高,或者load factor过低。
(3)WeakHashMap类
  WeakHashMap是一种改进的HashMap,它对key实行“弱引用”,如果一个key不再被外部所引用,那么该key可以被GC回收
  对集合操作的工具类
  Java提供了java.util.Collections,以及java.util.Arrays类简化对集合的操作
  java.util.Collections主要提供一些static方法用来操作或创建Collection,Map等集合。
  java.util.Arrays主要提供static方法对数组进行操作。。

1.总结:如果涉及到堆栈,队列等操作,应该考虑用List,对于需要快速插入,删除元素,应该使用LinkedList,如果需要快速随机访问元素,应该使用ArrayList。
  如果程序在单线程环境中,或者访问仅仅在一个线程中进行,考虑非同步的类,其效率较高,如果多个线程可能同时操作一个类,应该使用同步的类。
  在除需要排序时使用TreeSet,TreeMap外,都应使用HashSet,HashMap,因为他们 的效率更高。
  要特别注意对哈希表的操作,作为key的对象要正确复写equals和hashCode方法
  容器类仅能持有对象引用(指向对象的指针),而不是将对象信息copy一份至数列某位置。一旦将对象置入容器内,便损失了该对象的型别信息。
  尽量返回接口而非实际的类型,如返回List而非ArrayList,这样如果以后需要将ArrayList换成LinkedList时,客户端代码不用改变。这就是针对抽象编程。
2.一个Collection代表组Object(对象)的集合,Collection可以看作是(value)的集合,而Map可以看作是(key,value)的集合。
(1)规则集合(set):Set是最简单的一种集合对象不按特定的方式排序没有重复对象
       HashSet : HashSet类按照哈希算法来存取集合中的对象,存取速度比较快
  TreeSet : TreeSet类实现了SortedSet接口,能够对集合中的对象进行排序。
(2)线性表集合(list):对象按照索引位置排序(以线性方式存储),集合中可以有重复的对象。List 的特点是像数组一样的存储方式 使用下标读取
   ArrayList: 代表长度可以改变得数组。可以对元素进行随机的访问,向ArrayList()中插入与删除元素的速度慢。 
   LinkedList: 在实现中采用链表数据结构。插入和删除速度快,访问速度慢。 
(3)映射(map):Map 是一种把键对象和值对象映射的集合,它的每一个元素都包含一对键对象和值对象。键不可以重复,值可以重复。Map 的特点是使用键值对的存储方式 使用存储时设置的键(key)读取
    a.Hashmap继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value
    b.TreeMap则是对键按序存放,基于红黑树数据结构的实现。查看“键”或“键值对”时,它们会被排序(次序由Comparabel或Comparator决定)。TreeMap的特点在于,你得到的结果是经过排序的。TreeMap是唯一的带有subMap()方法的Map,它可以返回一个子树。
3.注意:
  1、Collection没有get()方法来取得某个元素。只能通过iterator()遍历元素。
  2、Set和Collection拥有一模一样的接口。
  3、List,可以通过get()方法来一次取出一个元素。使用数字来选择一堆对象中的一个,get(0)...。(add/get)
    4、一般使用ArrayList。用LinkedList构造堆栈stack、队列queue。
  5、Map用 put(k,v) / get(k),还可以使用containsKey()/containsValue()来检查其中是否含有某个key/value。
  HashMap会利用对象的hashCode(即哈希函数)来快速找到key。
  6、Map中元素,可以将key序列、value序列单独抽取出来。
  使用keySet()抽取key序列,将map中的所有keys生成一个Set。
  使用values()抽取value序列,将map中的所有values生成一个Collection。
  为什么一个生成Set,一个生成Collection?那是因为,key总是独一无二的,value允许重复。

二、Android中的List+Set+Map
1.Map(java.util.Map<K, V>)接口
(1)概述:一个Map就是一种把键对象和值对象映射的集合,它的每一个元素都包含一对键对象和值对象的映射。
(2)嵌入类:Map.Entry<K, V>接口,是一个映射在Map中的key/value键值对。
(3)常用方法:
    clear():移除Map集合中的所有元素
    containsKey(Object key):返回Map集合中指定的key
    containsValue(Object value) :返回Map集合中指定value值
    Set<Entry<K, V>> entrySet() :返回Map中所有的映射到一个set集合中
    get(Object key):返回指定key的value值
     int hashCode():返回一个迭代hash code
    isEmpty():判定map是否为空
    Set<K> keySet():获取Map集合中一组键对象到set集合
    put(K key, V value):为指定的key添加value
    putAll(Map<? extends K, ? extends V> map):复制当前Map集合到另一个Map集合
   remove(Object key):删除Map集合中的key
   size():获得Map集合中元素的个数
   values():获取Map集合中所有的value并返回到一个Collections集合中
2.HashMap( java.util.HashMap<K, V>)类
(1)概述:HashMap继承Map接口,实现一个key-value映射的哈希表。任何非空(non-null)的对象都可作为key或者value,添加数据使用put(key, value),取出数据使用get(key)。需要注意的是HashMap的迭代顺序是不确定的,如果需要确定的迭代则可以使用LinkedHashMap。另外,HashMap是不同步的。
(2)构造方法
HashMap():构造一个空的HashMap实例
HashMap(int capacity):构造一个带容量大小的HashMap实例
HashMap(int capacity, float loadFactor):构造一个带容量和load factor的HashMap实例
HashMap(Map<? extends K, ? extends V> map):构造一个从另一个Map复制过来的HashMap实例
(3)常用方法
void clear():删除Hash Map集合中的所有元素(映射)
boolean containsKey(Object key):判定Hash Map集合中是否包含指定的key
boolean containsValue(Object value):判定Hash Map集合中是否包含只指定的value
Set<Entry<K, V>> entrySet():将Hash Map集合中的所有映射返回到一个set集合中
V get(Object key):获得Hash Map集合中指定key对象的value
boolean isEmpty():判定Hash Map集合是否为空
Set<K> keySet():返回Hash Map集合中一组keys对象
V put(K key, V value):往Hash Map集合中添加一对键值对(元素)
void putAll(Map<? extends K, ? extends V> map):将一个Hash Map中的所有映射复制到另外一个map中
V remove(Object key):删除指定的key对象
int size():获得Hash Map集合中元素的个数
C ollection<V> values():返回hash map集合中所有的values到一个Collection集合
3.List(java.util.List<E>)接口
1.概要:List列表是一组有序数据的集合,每个元素(数据)在list集合中都有对应的一个索引点,每个元素都可以通过索引值查找并且相对于set集合来说元素值是可重复的。
2.公共方法(E代表类)
abstract boolean
add(E object)
Adds the specified object at the end of this List.
abstract void
add(int location, E object)
Inserts the specified object into this List at the specified location.
abstract boolean
addAll(Collection<? extends E> collection)
Adds the objects in the specified collection to the end of thisList.
abstract boolean
addAll(int location, Collection<? extends E> collection)
Inserts the objects in the specified collection at the specified location in this List.
abstract void
clear()
Removes all elements from this List, leaving it empty.
abstract boolean
contains(Object object)
Tests whether this List contains the specified object.
abstract boolean
equals(Object object)
Compares the given object with the List, and returns true if they represent the same object using a class specific comparison.
abstract E
get(int location)
Returns the element at the specified location in this List.
abstract int
hashCode()
Returns the hash code for this List.
abstract int
indexOf(Object object)
Searches this List for the specified object and returns the index of the first occurrence.
abstract boolean
isEmpty()
Returns whether this List contains no elements.
abstract Iterator<E>
iterator()
Returns an iterator on the elements of this List.
abstract E
remove(int location)
Removes the object at the specified location from this List.
abstract boolean
remove(Object object)
Removes the first occurrence of the specified object from thisList.
abstract boolean
removeAll(Collection<?> collection)
Removes all occurrences in this List of each object in the specified collection.
abstract E
set(int location, E object)
Replaces the element at the specified location in this List with the specified object.
abstract int
size()
Returns the number of elements in this List.
abstract Object[]
toArray()
Returns an array containing all elements contained in this List.
4.java.util.ArrayList<E>类
1.概要:ArrayList实现了可变大小的数组。它允许所有元素,包括null。ArrayList没有同步
2.构造函数:
ArrayList(int capacity):构造一个指定容量的ArrayList 实例
ArrayList():构造一个ArrayList 实例
ArrayList(Collection<? extends E> collection):构造一个包含另一个ArrayList 集合所有元素的实例
3.公共方法
boolean
add(E object)
Adds the specified object at the end of this ArrayList.
void
add(int index, E object)
Inserts the specified object into this ArrayList at the specified location.
boolean
addAll(Collection<? extends E> collection)
Adds the objects in the specified collection to this ArrayList.
boolean
addAll(int index, Collection<? extends E> collection)
Inserts the objects in the specified collection at the specified location in this List.
void
clear()
Removes all elements from this ArrayList, leaving it empty.
boolean
contains(Object object)
Searches this ArrayList for the specified object.
boolean
equals(Object o)
Compares the specified object to this list and return true if they are equal.
E
get(int index)
Returns the element at the specified location in this list.
int
hashCode()
Returns the hash code of this list.
boolean
isEmpty()
Returns if this Collection contains no elements.
Iterator<E>
iterator()
Returns an iterator on the elements of this list.
E
remove(int index)
Removes the object at the specified location from this list.
boolean
remove(Object object)
Removes one instance of the specified object from this Collection if one is contained (optional).
E
set(int index, E object)
Replaces the element at the specified location in this ArrayList with the specified object.
int
size()
Returns the number of elements in this ArrayList.
Object[]
toArray()
Returns a new array containing all elements contained in this ArrayList.
5.LinkedList(java.util.LinkedList<E>)类
(1)概述:LinkedList继承于List,与 ArrayList不同的是,LinkedList 在实现中采用链表数据结构.
(2)构造方法
 LinkedList():构造一个空的LinkedLists实例
Constructs a new empty instance of LinkedList.
LinkedList(Collection<? extends E> collection):利用一个Collection或其子类集合实例,构造一个包含另一个LinkedList集合所有元素的实例
(3)公共方法
boolean
add(E object)
Adds the specified object at the end of this LinkedList.
boolean
addAll(Collection<? extends E> collection)
Adds the objects in the specified Collection to this LinkedList.
void
addFirst(E object)
Adds the specified object at the beginning of this LinkedList.
void
addLast(E object)
Adds the specified object at the end of this LinkedList.
void
clear()
Removes all elements from this LinkedList, leaving it empty.
boolean
contains(Object object)
Searches this LinkedList for the specified object.
E
get(int location)
Returns the element at the specified location in this list.
E
getFirst()
Returns the first element in this LinkedList.
E
getLast()
Returns the last element in this LinkedList.
int
indexOf(Object object)
Searches this list for the specified object and returns the index of the first occurrence.
E
peek()
Retrieves, but does not remove, the head of the queue represented by this deque (in other words, the first element of this deque), or returns nullif this deque is empty.
E
poll()
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque), or returns null if this deque is empty.
E
pop()
Pops an element from the stack represented by this deque.
void
push(E e)
Pushes an element onto the stack represented by this deque (in other words, at the head of this deque) if it is possible to do so immediately without violating capacity restrictions, returning true upon success and throwing an IllegalStateException if no space is currently available.
E
remove()
Retrieves and removes the head of the queue represented by this deque (in other words, the first element of this deque).
E
set(int location, E object)
Replaces the element at the specified location in this LinkedList with the specified object.
int
size()
Returns the number of elements in this LinkedList.
Object[]
toArray()
Returns a new array containing all elements contained in this LinkedList.
6.Set(java.util.Set<E>)接口
(1)概述:Set是最简单的一种集合对象不按特定的方式排序,没有重复对象
(2)公共方法:
abstract boolean
add(E object)
Adds the specified object to this set.
abstract boolean
addAll(Collection<? extends E> collection)
Adds the objects in the specified collection which do not exist yet in this set.
abstract void
clear()
Removes all elements from this set, leaving it empty.
abstract boolean
contains(Object object)
Searches this set for the specified object.
abstract boolean
containsAll(Collection<?> collection)
Searches this set for all objects in the specified collection.
abstract boolean
equals(Object object)
Compares the specified object to this set, and returns true if they represent the same object using a class specific comparison.
abstract int
hashCode()
Returns the hash code for this set.
abstract boolean
isEmpty()
Returns true if this set has no elements.
abstract Iterator<E>
iterator()
Returns an iterator on the elements of this set.
abstract boolean
remove(Object object)
Removes the specified object from this set.
abstract boolean
removeAll(Collection<?> collection)
Removes all objects in the specified collection from this set.
abstract boolean
retainAll(Collection<?> collection)
Removes all objects from this set that are not contained in the specified collection.
abstract int
size()
Returns the number of elements in this set.
abstract <T> T[]
toArray(T[] array)
Returns an array containing all elements contained in this set.
abstract Object[]
toArray()
Returns an array containing all elements contained in this set.
另外,类HashSet<E>, LinkedHashSet<E>, NavigableSet<E>, SortedSet<E>, TreeSet<E>均继承于Set接口,它们之间的区别主要在于构成Set集合的方式不同。如HashSet类使用的是Hash数据结构构成的Set集合,而TreeSet<E>则是利用树构成Set集合,这种解释同样也使用与List和Map。
    List、Set、Map均为管理数据集合的一种方法,它们之间的主要区别在于集合元素是否可重复、集合的构成形式(如一个Collection代表一组Object(对象)的集合,Collection可以看作是(value)的集合,而Map可以看作是(key,value)的集合),仅此而已!
参考:
1.http://www.apkbus.com/forum.php?mod=viewthread&tid=13600
2.http://www.2cto.com/kf/201312/264821.html
3.http://wear.techbrood.com/reference/java/util/Set.html
0 0
原创粉丝点击