Java Basics-Collections

Source: Internet
Author: User
Tags comparable rehash

Collection

Collection Collection

In the Java.util package, which Collection contains:

    • List: Elements must be accommodated in a specific order
    • Set: cannot contain any duplicate elements

Note: Map not Collection in the collection.

CollectionThe Main method

    • Boolean Add (Object) : Returns &NBSP if not added; false ( Set   Common)
    • Boolean AddAll (Collection)
    • void Clear () : Clear All
    • Boolean contains (Object) : Contains (by comparison equals ) returns true
    • Boolean containsall (Collection) : Returns true if all are included
    • Boolean isEmpty () : no element returned true
    • Iterator Iterator () : Returns an iterator,    Collection   Unique Iteration method
    • Boolean Remove (Object) :   true   represents a delete action
    • Boolean RemoveAll (Collection) :   true   represents a delete action
    • Boolean retainall (Collection) : Take intersection, change return   true
    • int size ()
    • object[] ToArray () : Returns an array
    • object[] ToArray (object[] a)

1.8 New Features

    • Spliterator<E> spliterator()
    • Stream<E> stream()
    • Stream<E> parallelStream()
List

ListThe interface inherits from the Collection interface, which guarantees the order in which the elements are saved . Implementation classes are mainly:

    1. ArrayList
    2. LinkedList
ArrayList

Characteristics:

    • Used to replaceVector
    • Array implementations
    • Provides random access
    • Query Fast O (1), insert Delete slow

Expansion:

    • Initial value: 0
    • First growth: ' mincapacity = Math.max (default_capacity, mincapacity);
    • After each 3/2 * oldcapacity + 1:oldCapacity + (oldCapacity >> 1) + 1
LinkedList

Characteristics:

    • Bidirectional linked list implementation
    • Insert Delete Fast
    • Random lookup slow, time complexity O (n)
Set

SetThe interface inherits from the Collection interface, which guarantees the element uniqueness within the container and does not guarantee the order. the Set object that is added in, must override the equals() method (otherwise just compare the address), the implementation class has:

    1. HashSet
    2. TreeSet
HashSet

Characteristics:

    • Needhashcode
    • No guarantee order
    • HashMapeach add operation is invoked with the implementationmap.put(ele, 预定义假对象);
TreeSet

Characteristics:

    • Order of Guarantee
    • TreeMapis implemented, each add operation invokes themap.put(ele, 预定义假对象);
Map

Used to store "key-value pairs." Contains:

    1. HashMap
    2. TreeMap
HashMap

Characteristics:

    1. Used to replaceHashtable
    2. Need to rewrite hashCode() andequals()
    3. No guarantee order
    4. put()and get() for constant time

Expansion:

    1. Initial value: 16, load factor is 0.75, initial threshold value is 16*0.75
    2. Capacity doubles for each expansion

with the Hashtable difference :

    1. Non-thread safe, external (caller) guaranteed thread safety
    2. Allow storage<null, null>

parameters that affect HashMap performance :

Initial size and load factor , when (key value logarithmic > total number of Slots * load factor), will be carried out rehash() .

how to effectively reduce rehash the operation to improve HashMap performance? 1. When setting the initial size, consider how many elements are actually stored, and the growth factor (when to expand), so that you can reduce the number of rehash. 2. When there is a special number of elements to be stored, the initial value should consider the larger point of the setting. This is much more efficient than changing the size of each expansion.

TreeMap

Features: 1. Implemented on the basis of red-black trees. 2. key cannot be null, and HashMap differs by 3. There are subMap() methods that can return part of the tree. 4. put() and get() time complexity is log (N) 5. Need to rewrite equals() 6. Query HashMap faster

TreeMapHow are they sorted?

    1. Comparatorthe implementation of a constructor passed in an interface
    2. The storage Object implements the Comparable interface

__ Comparator and Comparable What is the difference? Comparator is an external comparator, its comparison method compare(T o1, T o2) has two parameters Comparable is an internal comparator, the comparison method has compareTo(T o) only one parameter

Common methods for sorting and searching array sorting
    1. CallArrays.sort(a, new Comparator(){...})
    2. If Object implements a Comparable call to theArrays.sort(a)
Array Search
    1. First sort
    2. and then callArrays.binarySearch()
List sort
    • Before JDK 1.8
      • Convert an array First:Object[] a = list.toArray()
      • Called Arrays.sort(a, new Comparator(){...}) , if Object implements a Comparable call to theArrays.sort(a)
    • After JDK 1.8, the method can be called void sort(Comparator c)
    • Calling Collections.sort(List l) methods
List Search

Collections.binarySearch(List, Object)

Set
    • Conversion array Sorting
      • Convert an array First:Object[] a = list.toArray()
      • Called Arrays.sort(a, new Comparator(){...}) , if Object implements a Comparable call to theArrays.sort(a)
    • will be HashSet converted intoTreeSet
Map
    • will be HashMap converted intoTreeMap
Other practical methods Collections
    1. enumeration(Collection)
    2. max(Collection)
    3. min(Collection)
    4. max(Collection, Comparator)
    5. min(Collection, Comparator)
    6. nCopies(int n, Object o): Returns a list of non-edges, with elements in the list pointing to O
    7. unmodifiedbleCollection(Collection): Returns a non-edge Collection
    8. synchronizedList(List)
    9. synchronizedSet(Set)
    10. synchronizedMap(Map)

What is the difference between enumeration and iterator interfaces?

The enumeration is twice times faster than iterator, and uses less memory. Enumeration is very basic and meets the needs of the foundation. However, iterator is more secure than enumeration because when a collection is being traversed, it blocks other threads from modifying the collection.

Iterators Replace enumeration In the Java collection framework. Iterators allow callers to remove elements from the collection, and enumeration cannot. To make its functionality clearer, the iterator method name has been improved.

Other container array

Pros: Can accommodate basic data types Cons: Allocating space ahead of time

Vector, Stack, Hashtablevector

Characteristics:

    • Implements the List interface
    • Thread safety, methods are synchronized identified, with significant performance overhead
    • Internally implemented with arrays

Expansion:

    • Initial value: 10 (default constructor)
    • Each expansion: Old + (capacityincrement==0 0:oldcapacity) + 1
Stack

Characteristics:

    • Inherit fromVector
    • First in and Out (LIFO)

Expansion, withVector

Hashtable

Characteristics:

    • Implements the Map interface
    • Storage key-value Pair
    • Array with inner class Entry<K,V> (implement M ap.Entry<K,V> interface) + External zipper method
    • Thread safety, by adding guarantees to the method synchronized

Expansion:

    • Initial value: 11 (default constructor), Load factor: 0.75
    • Expansion condition: Every time it rehash() will be enlarged
    • rehashCondition: count >= threshold The threshold value is: Current size * load factor
    • Each expansion:newCapacity = (oldCapacity << 1) + 1
    • Maximum not exceeding MAX_ARRAY_SIZE ( Integer.MAX_VALUE - 8 maximum-8)

What's the default hashcode ?

hashcodeThe default value is Object hashcode generated by, and the value is the address of the object.

Why do I want to rewrite and hashmap/hashlist/hashtable the objects to be stored in the object equals hashcode ?

    1. hashcodeThe default value is the address of the object, and if one object is in Hashtable , the other is found in an equal object, it cannot be Hashtable retrieved in, because two object addresses are different, so the retrieved Enties[index] is different.

    2. The reason to rewrite it equals is because although hashcode it is possible to find the correct entries[index] one, it is the comparison method to find the equal element in the list equals .

Java Basics-Collections

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.