List, Map, Set, a collection of java Daquan basis (list, set, map)

java set (list, set, map)

set

Set of arrays

Array (basic data types may be stored) is a container object for existential, but the length of the array is fixed, is not suitable for use in the number of objects is unknown.

Set (only store object, the object may not be the same type) of variable length, it may be used in most cases.
Note: Array told me we can look at previous blog

Relationship collection classes and interfaces

Collection interface is the root interface collection of classes, Java does not provide this direct interface implementation class. But let it be inherited produced two interfaces, it is the Set and List. Set can not contain duplicate elements. List is an ordered collection may contain duplicate elements, provides a way to access by index.

Map is another interface Java.util package, and it does not matter the Collection interface, independent of each other, but are part of a set of classes. Map contains key-value pairs. Map can not contain duplicate key, but can contain the same value.

Iterator set of all classes, have achieved Iterator interface, which is an interface for traversing a set of elements, comprising the following three main methods:
1. the hasNext () whether there is a next element.
2. Next () Returns the next element.
3. the Remove () to delete the current element.

list, set, map comparison

interface Sub-interfaces Are Ordered Whether to allow duplicate elements
Collection            no  
List    ArrayList no Yes
       LinkedList no Yes
       Vector no Yes
Set AbstractSet no no
   HashSet no no
   TreeSet Is (a binary sort tree) no
Map AbstractMap no Using the key-value store and the mapping data, key must be unique, value may be repeated
   HashMap   no
   TreeMap Is (a binary sort tree) Using the key-value store and the mapping data, key must be unique, value may be repeated

 

list (ordered, repeatable)

List of objects stored in an orderly, but also repeatable, List index is concerned, with a series of index and related methods, query speed. Because to list the collection insert or delete data, accompanied by moving back data, delete all data inserted slow.

ArrayList

  ArrayList array is based, at initialization ArrayList, builds empty array (Object [] elementData = {}). ArrayList is a disorder, which is arranged in the order added, of course, he also provides a sort method, if you need to sort ArrayList, you only need to call this method, it can provide Comparator comparator

add operation:

  1) If this is the first additive element, to the length of the array is the default Capacity expansion, i.e. 10.

  2) When is found while adding one or more elements, when the array length is not enough, on expansion, there are two cases:

  Add only one element, such as: capacity of the original array is 10, size 10 already and can not be added. Capacity is needed, new capacity = old capacity + old capacity >> 1 = 10 + 10/2 = 15. 15 i.e. the new capacity.

  When a plurality of elements simultaneously added, Capacity is the original array 10, size 10, when the six elements simultaneously added. It required 16 min capacity, and in accordance with capacity = old capacity + old capacity >> 1 = 10 + 10/2 = 15. new capacity less than min capacity, then take the min capacity.

  For add, if you do not specify the index, it is added directly to the back of array elements that do not involve moving, if you want to add to a particular position, it needs to be an element of this starting position moved back one position, then this location settings.

Remove operation:

 Remove offers two, according to the following standard and value.

  1) the Remove (int index) : first need to check Index is within a reasonable range. Secondly, after recalling elements of System.arraycopy the index to move forward.

  2) Remove (Object O) : First traverse the array, the same elements as the first acquisition, acquires the index element. Secondly, after recalling elements of System.arraycopy the index to move forward.

Get operations:

  This is relatively simple, can be operated directly on the array.

LinkedList

  LinkedList is based on the list, which is a doubly linked list, each node maintains a prev and next pointers. For this list at the same time, maintaining the first and last pointers, first point to the first element, last point to the last element. LinkedList is an unordered list, ordered according to the order of insertion and does not provide the sort method sorts the inner elements.

Add elements:

  LinkedList provides several methods to add elements: addFirst, addLast, addAll, add and the like, the time complexity is O (1).

Remove elements:

  LinkedList provides several methods for removing elements: removeFirst, removeLast, removeFirstOccurrence, remove the like, the time complexity is O (1).

Get elements:

  The subscript given index, it is determined first node, last direct distance, if index <size (number of array elements) / 2, starts from the first. If so, start from the last. This thinking and we usually are not the same, perhaps in accordance with our habits, from the first start. It would be a little careful optimization of it.

Traversal

In the following four classes focused on providing a common output:

1) Iterator: iterative output, it is the most used output.

2) ListIterator: sub Iterator interface, dedicated to the content output List.

3) foreach Output: new features provided after JDK1.5, may output an array or collection.

4) for circulation

Code examples are as follows:

for的形式:for(int i=0;i<arr.size();i++){...}

foreach form:  for (int I: ARR) {...}

iterator的形式:
Iterator it = arr.iterator();
while(it.hasNext()){ object o =it.next(); ...}

Set (unordered, can not be repeated)

Set in the object is stored in disorder, can not be repeated, the objects in the collection is not sorted in a particular way, simply put objects added to the collection.

HashSet

  HashSet HashMap is based on the achieved, the operation is very simple, more like a HashMap do a "package", and only use a HashMap to achieve a variety of key features, and the HashMap value is always PRESENT.

  HashSet does not allow duplicate (HashMap of key must be unique, if duplicate on the cover), allow null values, non-thread-safe.

Construction method

HashSet () 
  Constructs a new empty SET, default initial capacity thereof was 16 underlying HashMap instance, load factor is 0.75.
HashSet (Collection <? Extends E> 
c)   Constructs a new set containing the elements of the specified collection.
HashSet (int initialCapacity) 
  Constructs a new empty set, the backing HashMap instance with the specified initial capacity and a default load factor (0.75).
HashSet (int initialCapacity, float loadFactor)
  Constructs a new empty set, the backing HashMap instance with the specified initial capacity and the specified load factor.

method

boolean add (E e) 
  , if not yet included in this set of elements specified, add the specified element.
void clear ()
  Removes from this set all of the elements.
** Object clone () 
  returns a shallow copy of this HashSet instance: the elements themselves are not copied.
boolean contains (Object o) 
  if this set contains the specified element, it returns true.
boolean isEmpty () **
  if this set contains no elements, it returns true.
** Iterator iterator () 
  Returns the elements in this set iterator.
boolean remove (Object o) 
  if the specified element from this set, it is removed.
int size () **
  Returns the number of elements in this set (the set capacity).

TreeSet

  TreeMap of NavigableSet implementation. Using elemental natural order sort elements, sorting or when creating a Comparator provided SET, depending on the method of construction used.

  Constructors and methods more similar not to say

Traversing (and similar list)

Traversal of the set of

1. iterates over:

Set<String> set = new HashSet<String>(); Iterator<String> it = set.iterator(); while (it.hasNext()) { String str = it.next(); System.out.println(str); } 

2.for (foreach) loop through:

for (String str : set) {  
      System.out.println(str); } 

Map (key-value pairs, Unique, not unique)

  Map set of key-value pairs are stored, the key can not be repeated, the value may be repeated. Obtained according to the key value, set to obtain a set of key map set when traversal of traversal collection set, the corresponding value.

HashMap

  Array stored key / value, the thread non-secure , allowing key and a null value , not repeat key, value allowing repeated, does not guarantee element in the iteration sequence is in the order of insertion, hash value of the key is first key value calculated hashcode and then calculates, each time the capacity expansion will re-calculate the hash value of the key so, consumes resources, requires key must override equals method and hashcode

  16 default initial capacity, load factor 0.75, the old capacity expansion by 2, an element fast lookup, if the key value as the comparison, if the value is not the same, the stored value in accordance with the list structure, there is a plurality of back key value;

method

1, added:

  PUT V (K key, V value)  (key value may be the same, but the value will overwrite the previous value is added, the return value is the previous, if not returned null)

  putAll (Map <? extends K ,? extends V> m)  from a specified will map all of the mappings to this map (optional).

2, delete

  remove ()  delete the associated object that specifies the key target

  clear ()  Clear collection object

3, get

  value get (key)  may be used when determining whether the key is present. When the specified key does not exist, it returns null.

4, it is determined:

  boolean isEmpty ()  length of 0 returns true, false otherwise

  boolean containsKey (Object key)  determines whether the collection contains the specified key

  boolean containsValue (Object value)  determines whether the collection contains a specified value

4, length:

 Int size()

  The main way to map these on

Hashtable

  Hashtable and HashMap similar to HashMap is thread-safe version, which supports thread synchronization, that at any one time only one thread can write Hashtable, and therefore also led Hashtale in writing will be relatively slow, it inherited from the Dictionary class, different it is not allowed to record or key is null, while less efficient.

LinkedHashMap

LinkedHashMap preserve insertion order record, with Iteraor when traversing LinkedHashMap, to get the record must be inserted first, when traversing slower than HashMap, HashMap has all the features of.

TreeMap

  NavigableMap achieve ased on red and black, non-thread-safe, does not permit null, key can not be repeated, value Allow duplicates into the element TreeMap should implement the Comparable interface or Comparator interface to achieve, iterates the elements in the order sorted, two a comparison key must not throw classCastException. The main elements of the time for deposit to automatically sort the elements, when the output of the iteration on the output in sorted order

Traversal

The first: KeySet ()
  the Map all the keys into the set collection. Because the set with an iterator. All iterative manner can remove all the keys, then according to the get method. Obtaining a value corresponding to each key. keySet (): After iteration can only get () to take key.
  The result will be taken out of order, because the data line acquired when the primary key used HashMap.keySet () method, and this method returns the result Set, which scrambled data is discharged.

    Map map = new HashMap();
    map.put("key1","lisi1"); map.put("key2","lisi2"); map.put("key3","lisi3"); map.put("key4","lisi4"); //先获取map集合的所有键的set集合,keyset() Iterator it = map.keySet().iterator(); //获取迭代器 while(it.hasNext()){ Object key = it.next(); System.out.println(map.get(key)); }

The second: values ()  Gets all values.
Collection values () can not get to the key objects

        Collection<String> vs = map.values();
        Iterator<String> it = vs.iterator();
        while (it.hasNext()) {
            String value = it.next(); System.out.println(" value=" + value); }

Third: the entrySet ()
Set <of Map.Entry <K, V >> the entrySet () // Returns mappings in this map contains a Set view. (A relationship that is a key - value pair) is the (key-value) as a whole, one-to-ground storage to Set among a collection. Map.Entry represent mappings. entrySet (): After the iteration may e.getKey (), e.getValue () are two ways to get key and value. Entry is returned interface.
A typical usage is as follows:

// 返回的Map.Entry对象的Set集合 Map.Entry包含了key和value对象
        Set<Map.Entry<Integer, String>> es = map.entrySet();

        Iterator<Map.Entry<Integer, String>> it = es.iterator(); while (it.hasNext()) { // 返回的是封装了key和value对象的Map.Entry对象 Map.Entry<Integer, String> en = it.next(); // 获取Map.Entry对象中封装的key和value对象 Integer key = en.getKey(); String value = en.getValue(); System.out.println("key=" + key + " value=" + value); }

  The third embodiment is recommended, i.e., the entrySet () method, a higher efficiency.
  For keySet actually traversed twice, once into iterator, one that is removed from the value key for the HashMap. The entryset just traversing the first time, it is the key and value are placed in the entry, so fast. Two kinds of traversal of traversal time difference is obvious.

to sum up:

Vector和ArrayList

  1, vector is a thread synchronization, so it is thread-safe, but arraylist is asynchronous thread is unsafe. If you do not take into account safety factors threads, usually with arraylist more efficient.

  2, if the number of elements of the set current set greater than the length of the array, vector current growth rate of 100% of the length of the array, and the growth rate of 50% arraylist current length of the array. If a large amount of data in the data set, with a vector has certain advantages.

  3, if the data to find a specific location, time, vector arraylist and use the same, or if you frequently accessed data, this time using the vector and the arraylist can be. And if the move will lead to a specific location behind the element are moved, this time should take into account the use linklist, because other elements do not move when it moves data a specified location.

  ArrayList and Vector is the use of an array of stored data, this number of array elements is greater than data actually stored in order to increase and insertion elements, allows direct serial index element, but the insert data to be directed to the array elements move like a memory operation, the index data fast, slow insert data, Vector method since a synchronized (thread-safe) so the worse performance than ArrayList, the LinkedList implemented using a doubly linked list is stored, indexed by serial number data requires traversing forward or backward, but only needs to insert the data recording according to the present before and after the keys to entry, so insert several fast.

arraylist和linkedlist

  1.ArrayList data structure is implemented based on dynamic array, LinkedList based linked list data structure.

  2. For random access get and set, ArrayList feel better than LinkedList, because LinkedList to move the pointer.

  3. For new and delete operations add and remove, LinedList comparative advantage, because ArrayList to move data. This depends on the actual situation. If only for a single insertion or deletion of data, ArrayList speed but better than LinkedList. But if the bulk of random insertion and deletion of data, LinkedList speed is much better than ArrayList. ArrayList because every piece of data is inserted, to move the insertion point and all data after.

HashMap与TreeMap

  1, HashMap by its hashcode quickly find content, and TreeMap all the elements have maintained a certain fixed order, if you need to get an ordered result you should use TreeMap (the order of the elements is not HashMap stable).

  2, in the Map insertions, deletions and positioning elements, the HashMap is the best choice. But if you Yaoan natural order or custom order traversal key, then TreeMap will be better. Use HashMap require the addition of a clear definition of the key class hashCode () and equals () implementation.

  As two elements of the map, but the order is not the same, resulting in hashCode (not) different.

  Do the same test:
    in the HashMap same map values, different order, equals the time, to false;
    in TreeMap, the map the same values, different order, when equals, true, description, TreeMap when equals () is I put together a sequence of.

HashTable与HashMap

  1, synchronization: Hashtable is thread safe, that is synchronized, and HashMap line program is unsafe, not synchronized.

  2, HashMap allowed to null a key, a plurality of the null value.

  3, hashtable of key and value are not allowed to be null.

 

Guess you like

Origin www.cnblogs.com/ysySelf/p/10973355.html