With you know: Java collection of "family"

First to a collection of "family photo"

Collection is an interface, all of its subclasses (also interfaces) need to rewrite all of its way!

Special Note:
Collection and Collections too much like a long, confusing, special instructions here:

Collection
Collection 是集合的顶级接口(Iterable是JDK1.5新增),其定义了一些必要方法。如下:
     |-- iterator  //获取集合迭代器对象
     |-- size  //获取集合长度

     |-- add  //添加集合元素
     |-- addAll  //添加集合元素

     |-- remove  //删除集合元素
     |-- removeAll  //删除集合元素
     |-- clear  //清空集合元素

     |-- contains  //判断集合中是否包含某个元素
     |-- containsAll  //判断集合中是否包含某个元素
     |-- isEmpty  //判断集合是否有元素
     |-- equals  //判断两个集合是否相等

     |-- retainAll  //获取两个集合中相同的元素,存到调用者的容器中,相当于:替换调用者原来的元素
     |-- hashCode  //获取集合哈希码值
     |-- toArray  // 获取集合迭代器对象
Collections
Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。
此类不能实例化。就像一个工具类,服务于Java的Collection框架。常用方法说明如下:
     |-- sort(List<T> list)  //对 List集合进行排序(默认的是升序排列)(不适用与 Set集合)
     |--  sort(List<T> list, Comparator<? super T> c)  //对 List集合进行排序(可以传递自定义的比较器)(不适用与 Set集合)

     |-- shuffle(List<?> list)  // 对 List 集合中的元素进行随机排列

     |-- binarySearch(List<? extends T> list, T key)  //折半查找

     |-- reverse(List<?> list)  //反转 List 集合

     |-- reverseOrder()  //逆转对象的自然顺序 或 比较器

Collection introduces a collection of factions

List factions

  1. Ordered (deposit, taken in the same order - how to do it, how to take)
  2. An index (operation data can accurately index)
  3. It allows repeated storage element
  • ArrayList
    • Underlying data structure: a variable-length array (array itself invariable length), the length is 10 initialization (variable principles: for expansion of the array by copying, expansion rate: 50%).
    • Thread-safe, fast
    • Query speed, slow additions and deletions
  • LinkedList
    • Underlying data structure: the structure of the list (using the address recording position between the objects)
    • Thread-safe, fast
    • Slow queries, additions and deletions fast speed
  • The Vector (the Vector substituted the ArrayList)
    • Underlying data structure is a variable length array (ArrayList and the same, except that the expansion rate: 100%).
    • Thread safety, running slow
    • Query speed, slow additions and deletions

Set factions

  1. Disorder (deposit, withdraw the order may be different)
  2. No index
  3. Storage is not repeating elements
  • HashSet (disorder)
    • Singlet list of links
    • Underlying data structure: a hash table (actually a HashMap instance, may be prepared according to the underlying source code: the bottom layer is a HashMap)
    • Thread-safe, fast
      • LinkedHashSet (ordered)
        • LinkedHashSet began JDK1.4, Set began in JDK1.2
        • Doubly-linked list, based on the underlying implementation of a linked list hash table
        • Having predictable iteration order (deposit, withdraw the same order)
        • Thread-safe, fast, fast access speed
  • TreeSet (ordered and only)
    • Based on underlying data structure: black tree
    • You can sort the stored elements
    • Thread-safe, fast

Map collection of factions

  1. Key-value using the key-value to be mapped is stored.
  2. key is disordered, the only, value is not the only disorder.
  • HashMap (disorder)
    • Underlying data structure: a hash table
    • Thread-safe, fast, fast access speed
    • Allow the storage 'null' value, 'null' key
      • LinkedHashMap
        • Underlying data structure: a hash table
        • Iterative key sequence (deposit, consistent with the order taking)
        • Thread-safe, fast
  • TreeMap (ordered)
    • Substructure: red-black trees (can be sorted according to the natural order of the objects)
    • Key (Object): must have a natural order, or using a comparator (as keys used must have a natural sequence or a comparator, otherwise error)
    • Thread-safe, fast
  • The HashTable (disorder, HashTable is substituted HashMap)
    • Underlying data structure: a hash table
    • Key (Object): must override methods: hashCode (), equals ()
    • Allowed deposit 'null' (keys, values ​​are allowed to 'null', if kept 'null', given no compile time, run time throws a null pointer exception)
    • Thread safety, running slow
      • The Properties (disorder)
        • Underlying data structure: a hash table
        • Do not allow duplicate keys
        • Deposit, withdraw indeterminate order (unordered)
        • Thread safety, running slow

Common data structure (data storage)

Stack: advanced after the data
queues: Data FIFO
array: in accordance with the stored index
list: storing data, in accordance with the address records stored in a manner (in front of or behind the back remember the foregoing in mind and so on)
Tree: data stored in vessel tree structure as above, the object can be sorted (red-black tree)
hash table: storing a hash value object dependency object

Iteration Map collection (traversing)

Iteration step

    1. Using a collection method: iterator () Gets iterator object (acquired achieve Iterator interface class object).
    1. Use iterator object, invoke methods hasNext (), next () set of traversal.

Two ways iterative

  • Method 1: KeySet ways (Features: less code, the principle is simple, commonly used in development)
HashMap<String, Integer> map = new HashMap<>();
//获取所有的键'key', 存储到 Set 集合中
Set<String> keys = map.keySet(); 
Iterator<String> iterator = keys.iterator();
while (iterator.hasNext()) {
    String key = iterator.next();
    Integer value = map.get(key);
}
  • Second way: entrySet way
HashMap<String, String> map = new HashMap<>();
Set<Map.Entry<String, String>> entries = map.entrySet();
Iterator<Map.Entry<String, String>> iterator = entries.iterator();
while (iterator.hasNext()) {
    Map.Entry<String, String> entry = iterator.next();
    String key = entry.getKey();
    String value = entry.getValue();
}

Iteration Description

  • Get iterator object, has a value within lastRet iterator object (which may be viewed as a pointer), its original value is -1,
  • hasNext (): determining whether the pointer has data, returns true, no returns false
  • next (): pointer to a rearward position, acquires the current position data and returns
  • Special Note: once hasNext () can only be judged once next () call Each call next () pointer will move backward one!
//错误代码如示:
while (iterator.hasNext()) {
    System.out.println(iterator.next()+"..."+map.get(iterator.next()));
}

Iterative Methods for
each class that implements Collection collection, its interior is different. Therefore subclass for each set, the way they store objects are different. Each class defines a set of internal sub-class (Itr) to achieve the Iterator interface and override method each implement query, the acquired operation.

//以 ArrayList 为列,其内部重写了 Collection 的方法 iterator() 
//并返回实现了 Iterator 接口的内部类对象
public Iterator<E> iterator() {
    return new Itr();
}

/************************************************************/
//Java Iterator 接口源码中: 4个方法 (能看到的只有4个)
public interface Iterator<E> {
    //查找集合中是否还有下一个元素,有则返回true, 没有返回false
    boolean hasNext(); 
    //返回集合中的下一个元素
    E next();
    //遍历过程中,移除集合中的元素
    default void remove() {
            throw new UnsupportedOperationException("remove");
    }

    default void forEachRemaining(Consumer<? super E> action) { 
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

Map Collection and the difference between (Map: Mapping key-value pairs)

  1. Map is not inherited from the Collection interface (Map Collection and are top-level interface)
  2. Map a value corresponding to a key (not repeat key, value may be repeated)
  3. Map: All sub-interface or class, when the object is stored, each store two objects (keys and values) (the Add)
  4. Collection: All interface or sub-classes, each can store an object (value) (PUT)
  5. Map is a two-column, Collection is a single row

Distinction Array (array) and ArrayList (sets)

Array: Array

  • Representation: int [] array = new int [3] or int [] array = {1,2,3,4,5}
  • Data: change, check. The length of the fixed size! In memory it is continuous, fast, easy to operate

Collection: ArrayList

  • Representation: ArrayList list = new ArrayList();
  • Data: can add, delete, change,. Length size can grow dynamically

Guess you like

Origin www.cnblogs.com/io1024/p/11532696.html