java collection——源码分析

来源:互联网 发布:java 字符串特殊符号 编辑:程序博客网 时间:2024/05/21 19:46

最近开始整理一下collection框架,从源码着手,分析了一下,框架图如下


下面我们来看一张比较简单的表格,以区分各个类的差别:



List的方法:(源码,适合英语能力强的人读,更有利于学习)

package java.util;public interface List<E> extends Collection<E> {    /**   return the number of elements in this list     */  int size();    /**       return <tt>true</tt> if this list contains no elements     */   boolean isEmpty();    /**     * Returns <tt>true</tt> if this list contains the specified element.     */   boolean contains(Object o);    /**     * Returns an iterator over the elements in this list in proper sequence.     */   Iterator<E> iterator();    /**     * Returns an array containing all of the elements in this list in proper     */   Object[] toArray();    /**     * Returns an array containing all of the elements in this list in     * proper sequence (from first to last element); the runtime type of     * the returned array is that of the specified array.  If the list fits     * in the specified array, it is returned therein.  Otherwise, a new     * array is allocated with the runtime type of the specified array and     * the size of this list.     */    <T> T[] toArray(T[] a);    // Modification Operations    /**     * Appends the specified element to the end of this list (optional     * operation).     */  boolean add(E e);    /**     * Removes the first occurrence of the specified element from this list,     * if it is present (optional operation).  If this list does not contain     * the element, it is unchanged.  More formally, removes the element with     * the lowest index <tt>i</tt> such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>     * (if such an element exists).  Returns <tt>true</tt> if this list     * contained the specified element (or equivalently, if this list changed     * as a result of the call).     */     boolean remove(Object o);        /**     * Returns <tt>true</tt> if this list contains all of the elements of the     * specified collection.     */    boolean containsAll(Collection<?> c);    /**     * Appends all of the elements in the specified collection to the end of     * this list, in the order that they are returned by the specified     * collection's iterator (optional operation).  The behavior of this     * operation is undefined if the specified collection is modified while     * the operation is in progress.  (Note that this will occur if the     * specified collection is this list, and it's nonempty.)     */   boolean addAll(Collection<? extends E> c);    /**     * Inserts all of the elements in the specified collection into this     * list at the specified position (optional operation).  Shifts the     * element currently at that position (if any) and any subsequent     * elements to the right (increases their indices).  The new elements     * will appear in this list in the order that they are returned by the     * specified collection's iterator.  The behavior of this operation is     * undefined if the specified collection is modified while the     * operation is in progress.  (Note that this will occur if the specified     * collection is this list, and it's nonempty.)     */   boolean addAll(int index, Collection<? extends E> c);    /**     * Removes from this list all of its elements that are contained in the     * specified collection (optional operation).     */    boolean removeAll(Collection<?> c);
    /**     * Retains only the elements in this list that are contained in the     * specified collection (optional operation).  In other words, removes     * from this list all the elements that are not contained in the specified     * collection.     */     boolean retainAll(Collection<?> c);    /**     * Removes all of the elements from this list (optional operation).     * The list will be empty after this call returns.     */     void clear();    // Comparison and hashing    /**     * Compares the specified object with this list for equality.  Returns     */    <strong>boolean equals(Object o);</strong>    /**     * Returns the hash code value for this list.  The hash code of a list     * is defined to be the result of the following calculation:     */    int hashCode();    // Positional Access Operations    /**     * Returns the element at the specified position in this list.     */   E get(int index);    /**     * Replaces the element at the specified position in this list with the     * specified element (optional operation).     */   E set(int index, E element);    /**     * Inserts the specified element at the specified position in this list     * (optional operation).  Shifts the element currently at that position     * (if any) and any subsequent elements to the right (adds one to their     * indices).     */   void add(int index, E element);    /**     * Removes the element at the specified position in this list (optional     * operation).  Shifts any subsequent elements to the left (subtracts one     * from their indices).  Returns the element that was removed from the     * list.     */    E remove(int index);    // Search Operations    /**     * Returns the index of the first occurrence of the specified element     * in this list, or -1 if this list does not contain the element.     * More formally, returns the lowest index <tt>i</tt> such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,     * or -1 if there is no such index.     */   int indexOf(Object o);    /**     * Returns the index of the last occurrence of the specified element     * in this list, or -1 if this list does not contain the element.     * More formally, returns the highest index <tt>i</tt> such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,     * or -1 if there is no such index.     */    int lastIndexOf(Object o);    /**     * Returns a list iterator over the elements in this list (in proper     * sequence).     */   ListIterator<E> listIterator();    /**     * Returns a list iterator of the elements in this list (in proper     * sequence), starting at the specified position in this list.     */    ListIterator<E> listIterator(int index);    /**     * Returns a view of the portion of this list between the specified     */    List<E> subList(int fromIndex, int toIndex);}
List的常用方法:(翻译版)
 // 向列表的尾部追加指定的元素          list.add("lwc");          // 在列表的指定位置插入指定元素          list.add(1, "nxj");          // 追加指定 collection 中的所有元素到此列表的结尾          list.addAll(new ArrayList());          // 从列表中移除所有元素          list.clear();          // 如果列表包含指定的元素,则返回true          list.contains("nxj");          // 如果列表包含指定 collection 的所有元素,则返回 true          list.containsAll(new ArrayList());          // 比较指定的对象与列表是否相等          list.equals(new ArrayList());          // 返回列表中指定位置的元素          list.get(0);          // 返回列表的哈希码值          list.hashCode();          // 返回列表中首次出现指定元素的索引,如果列表不包含此元素,则返回 -1          list.indexOf("lwc");          // 返回列表中最后出现指定元素的索引,如果列表不包含此元素,则返回 -1          list.lastIndexOf("lwc");          // 如果列表不包含元素,则返回 true          list.isEmpty();          // 移除列表中指定位置的元素          list.remove(0);          // 移除列表中出现的首个指定元素          list.remove("lwc");          // 从列表中移除指定 collection 中包含的所有元素          list.removeAll(new ArrayList());          // 用指定元素替换列表中指定位置的元素          list.set(0, "lp");          // 返回列表中的元素数          list.size();          // 返回列表中指定的fromIndex(包括)和toIndex(不包括)之间的部分视图          list.subList(1, 2);          // 返回以正确顺序包含列表中的所有元素的数组          list.toArray();          // 返回以正确顺序包含列表中所有元素的数组          list.toArray(new String[] { "a", "b" });  

Set的方法:(源码,适合英语能力强的人读,更有利于学习)

public interface Set<E> extends Collection<E> {    // Query Operations    /**     * Returns the number of elements in this set (its cardinality).  If this     */   int size();    /**     * Returns <tt>true</tt> if this set contains no elements.     */    boolean isEmpty();    /**     * Returns <tt>true</tt> if this set contains the specified element.     */   boolean contains(Object o);    /**     * Returns an iterator over the elements in this set.  The elements are     * returned in no particular order (unless this set is an instance of some     * class that provides a guarantee).     */   Iterator<E> iterator();    /**     * Returns an array containing all of the elements in this set.     */  Object[] toArray();    /**     * Returns an array containing all of the elements in this set; the     * runtime type of the returned array is that of the specified array.     */   <T> T[] toArray(T[] a);    // Modification Operations    /**     * Adds the specified element to this set if it is not already present     * (optional operation).  More formally, adds the specified element     * <tt>e</tt> to this set if the set contains no element <tt>e2</tt>     * such that     * <tt>(e==null ? e2==null : e.equals(e2))</tt>.     */   boolean add(E e);    /**     * Removes the specified element from this set if it is present     * (optional operation).  More formally, removes an element <tt>e</tt>     * such that     * <tt>(o==null ? e==null : o.equals(e))</tt>, if     * this set contains such an element.  Returns <tt>true</tt> if this set     * contained the element (or equivalently, if this set changed as a     * result of the call).  (This set will not contain the element once the     * call returns.)     */   boolean remove(Object o);    // Bulk Operations    /**     * Returns <tt>true</tt> if this set contains all of the elements of the     * specified collection.  If the specified collection is also a set, this     * method returns <tt>true</tt> if it is a <i>subset</i> of this set.     */     boolean containsAll(Collection<?> c);    /**     * Adds all of the elements in the specified collection to this set if     * they're not already present (optional operation).  If the specified     * collection is also a set, the <tt>addAll</tt> operation effectively     * modifies this set so that its value is the <i>union</i> of the two     * sets.  The behavior of this operation is undefined if the specified     * collection is modified while the operation is in progress.     */    boolean addAll(Collection<? extends E> c);    /**     * Retains only the elements in this set that are contained in the     * specified collection (optional operation).  In other words, removes     * from this set all of its elements that are not contained in the     * specified collection.  If the specified collection is also a set, this     * operation effectively modifies this set so that its value is the     * <i>intersection</i> of the two sets.     */   boolean retainAll(Collection<?> c);    /**     * Removes from this set all of its elements that are contained in the     * specified collection (optional operation).  If the specified     * collection is also a set, this operation effectively modifies this     * set so that its value is the <i>asymmetric set difference</i> of     * the two sets.     */    boolean removeAll(Collection<?> c);    /**     * Removes all of the elements from this set (optional operation).     * The set will be empty after this call returns.     */   void clear();    // Comparison and hashing    /**     * Compares the specified object with this set for equality.      */   boolean equals(Object o);    /**     * Returns the hash code value for this set.      */   int hashCode();}

List的遍历:
        // 方法一  使用迭代器        Iterator<Map<Integer, String>> ite1 = list.iterator();          while (ite1.hasNext()) {              Map<Integer, String> m = ite1.next();              System.out.println(m);          }          // 方法二:  直接遍历        for (Map<Integer, String> m : list) {              System.out.println(m);          }  

扩展:Map(包含了HashMap, TreeMap, LinkedHashMap, Hashtable

Map是一种把键对象和值对象进行关联的容器,而一个值对象又可以是一个Map,依次类推,这样就可形成一个多级映射。对于键对象来说,像Set一样,一个Map容器中的键对象不允许重复,这是为了保持查找结果的一致性;如果有两个键对象一样,那你想得到那个键对象所对应的值对象时就有问题了,可能你得到的并不是你想的那个值对象,结果会造成混乱,所以键的唯一性很重要,也是符合集合的性质的。当然在使用过程中,某个键所对应的值对象可能会发生变化,这时会按照最后一次修改的值对象与键对应。对于值对象则没有唯一性的要求。你可以将任意多个键都映射到一个值对象上,这不会发生任何问题(不过对你的使用却可能会造成不便,你不知道你得到的到底是那一个键所对应的值对象)。Map有两种比较常用的实现:HashMap和TreeMap。HashMap也用到了哈希码的算法,以便快速查找一个键,TreeMap则是对键按序存放,因此它便有一些扩展的方法,比如firstKey(),lastKey()等,你还可以从TreeMap中指定一个范围以取得其子Map。键和值的关联很简单,用pub(Object key,Object value)方法即可将一个键与一个值对象相关联。用get(Object key)可得到与此key对象所对应的值对象。



Map的遍历:

方法一 在for-each循环中使用entries来遍历

这是最常见的并且在大多数情况下也是最可取的遍历方式。在键值都需要时使用。

[java] view plain copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. for (Map.Entry<Integer, Integer> entry : map.entrySet()) {  
  4.   
  5.     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
  6.   
  7. }  

 

方法二 在for-each循环中遍历keys或values。

如果只需要map中的键或者值,你可以通过keySet或values来实现遍历,而不是用entrySet。

[java] view plain copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. //遍历map中的键  
  4.   
  5. for (Integer key : map.keySet()) {  
  6.   
  7.     System.out.println("Key = " + key);  
  8.   
  9. }  
  10.   
  11. //遍历map中的值  
  12.   
  13. for (Integer value : map.values()) {  
  14.   
  15.     System.out.println("Value = " + value);  
  16.   
  17. }  

 

方法三使用Iterator遍历

使用泛型:

[java] view plain copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();  
  4.   
  5. while (entries.hasNext()) {  
  6.   
  7.     Map.Entry<Integer, Integer> entry = entries.next();  
  8.   
  9.     System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());  
  10.   
  11. }  


不使用泛型:

[java] view plain copy
  1. Map map = new HashMap();  
  2.   
  3. Iterator entries = map.entrySet().iterator();  
  4.   
  5. while (entries.hasNext()) {  
  6.   
  7.     Map.Entry entry = (Map.Entry) entries.next();  
  8.   
  9.     Integer key = (Integer)entry.getKey();  
  10.   
  11.     Integer value = (Integer)entry.getValue();  
  12.   
  13.     System.out.println("Key = " + key + ", Value = " + value);  
  14.   
  15. }  


你也可以在keySet和values上应用同样的方法。

该种方式看起来冗余却有其优点所在。首先,在老版本java中这是惟一遍历map的方式。另一个好处是,你可以在遍历时调用iterator.remove()来删除entries,另两个方法则不能。根据javadoc的说明,如果在for-each遍历中尝试使用此方法,结果是不可预测的。

从性能方面看,该方法类同于for-each遍历(即方法二)的性能。

 

方法四、通过键找值遍历(效率低)

[java] view plain copy
  1. Map<Integer, Integer> map = new HashMap<Integer, Integer>();  
  2.   
  3. for (Integer key : map.keySet()) {  
  4.   
  5.     Integer value = map.get(key);  
  6.   
  7.     System.out.println("Key = " + key + ", Value = " + value);  
  8.   
  9. }  

1 0
原创粉丝点击