The collection of algorithm (pre-order)--java

Source: Internet
Author: User
Tags comparable set set

Novice humble opinion, hope please correct: Attach the JDK Reference document: Link: pan.baidu.com/s/1elqg4etxysty1-ixmqqa4q Password: 33x0 and algorithm full text link www.cnblogs.com/nullering/p/ 9536339.html

A: Preface

Having said the basic cognition of data structure, I want to pull out a collection of--java. The collection of Java is just a container of objects that can be put in place, and these containers are implemented using different data structures, which are our best tools when we use the Java language.

, this is the abstract class of the collection of Java and the concrete implementation class, the abstract interface class cannot be instantiated and must be instantiated by the concrete implementation class.

Second: List interface and its implementation class ArrayList

A list is a set of elements that are ordered and can be duplicated, called a sequence

The list can control exactly where each element is inserted, or delete a location element

Basic operation:

(1), add

void Add (int Index, E Element): Inserts an element at the specified position in the list

void AddAll (int index, COLLECTION<?) Extends e> E): Inserts all elements from the specified collection to the specified position in the list

(2), delete

E Remove (int Index): Deletes the element at the specified position and returns the element;

(3), modify

e Set (int index, E Element): Replaces the element at the specified position and returns the replaced element

(4), obtain

Int indexOf (Object O): Returns the index of the first occurrence of the specified element, or 1 if it is not included in the list;

E get (int Index): Returns the element at the specified position;

list<e> sublist (int fromIndex, int toindex): Returns a partial view (list) between the specified FromIndex (inclusive) and Toindex (not included) in the list;

Implementing Class ArrayList (Common)

arraylist--array sequence, which is an important implementation class of List

ArrayList the bottom layer is implemented by arrays and can dynamically increase capacity

Refer to the JDK reference documentation for specific operations

Implementing Class LinkedList

LinkedList is based on linked lists and is a two-way loop list. is not thread-safe.

Refer to the JDK reference documentation for specific operations

Three: set interface and its implementation class

  

The set set is a sub-interface of the collection, and set does not allow its data elements to recur, meaning that each data element in the set is unique.

Although the collection is supposed to store Java objects, it does not actually put the Java objects in the Set collection, only the references to those objects in the Set collection. That is, the Java collection is actually a collection of multiple reference variables that point to the actual Java object.

Basic operation:

Implementing Class HashSet (Common)

  HashSet through the hash algorithm to arrange the elements within the set, the so-called hash algorithm is the arbitrary length of the input (also known as pre-mapping), through the hash algorithm, transformed into a fixed-length output, the output is the hash value. This conversion is a compression map. For different types of information, the hash value formula is not exactly the same.

When we use HashSet to store custom classes, we need to override the Equals and Hashcode methods in a custom class, mainly because there are no duplicate data elements allowed in the collection, and when the collection verifies the validity of the element (data elements are not repeatable), You need to invoke equals and hashcode validation.

Please refer to the documentation for specific methods

Implementing Class TreeSet

TreeSet can ensure that the collection element is in the sorted state. TreeSet uses a red-black tree's data structure to store collection elements.

TreeSet invokes the CompareTo (Object O) method of the collection element to compare the size relationship between elements, and then arranges the collection elements in ascending order, which is a natural sort.
Java provides a comparable interface that defines a CompareTo (object o) method that returns an integer value that the class implementing the interface must implement , and the object of the class that implements the interface can be compared in size. When an object calls the method to compare with another object, for example: Obj1.compareto (OBJ2), if the method returns 0, the two objects are equal, and if the method returns a positive integer, the obj1 is greater than obj2, or if the method returns a negative integer, Indicates that obj1 is less than obj2.

1 @Override2      Public intCompare (People O1, people O2) {3         //first by age, if the age is equal, by name4         if(O1.getage () = =o2.getage ())5             returno1.getname (). CompareTo (O2.getname ());6         Else7             returnO1.getage ()-o2.getage ();8}

Other methods refer to JDK documentation

Four: Queue interface and its implementation class

As the name implies, queue is used to simulate the data structure of queues. Queue FIFO first.

The queue interface has a Priorityqueue implementation class. In addition, the queue also has a deque interface, deque represents a "double-ended queue", the double-ended queue can be removed from both ends at the same time or add elements, so deque can be used as a stack. Java provides the Arraydeque implementation class and the LinkedList implementation class for Deque.

Several methods are defined in the queue interface:

void Add (Object e): inserts the specified element into the tail of the queue.

object Element (): Gets the element of the queue header, but does not delete the element.

Boolean offer (Object e): inserts the specified element into the tail of this queue. This method is usually more effective than add (Object e) When using a queue with limited capacity.

Object Peek (): returns the element at the head of the queue, but does not delete the element. If the queue is empty, NULL is returned.

Object Poll (): returns the element of the queue header and deletes the element. If the queue is empty, NULL is returned.

Object Remove (): Gets the element of the queue header and deletes the element.

Priorityqueue Implementation Class

Priorityqueue is a relatively standard queue implementation class. The reason for the comparison is that the order in which the Priorityqueue saves the queue elements is not in the order in which they are queued, but instead is reordered by the size of the queue elements. So when you call peek () or the poll () method, the elements in the queue are usually the smallest elements.

Priorityqueue does not allow you to insert null elements, but also to sort the queue elements. Refer to JDK documentation for specific methods

Five: Map interface and its implementation class

    • Map provides a mapping relationship in which elements are stored as key-value pairs (Key-value) that enable quick lookup of value based on key;
    • Key values are not repeatable, value values can be duplicated, and a value can be mapped to a number of key values, and each build can map to only one value
    • The order of the elements in the MAP depends on the order in which the iterators are iterated, and some implementation classes guarantee the order in which the elements are entered and exported, such as TREEMAP, while some implementation classes are unordered, such as HashMap.
    • Key,value can be any reference type of data, including null

Common methods:

1. Add:
V Put (K key, V value) (can be the same key value, but the added value will be
Cover front, return value is previous, if not return null)
Putall (map<? extends K,? extends v> m) close all mappings from the specified mappings
The system is copied to this map (optional operation).
2. Delete
Remove () Deletes the associated object, specifying the Key object
Clear () empties the collection object
3. Get
Value get (key); Can be used to determine if a key exists. When the specified key does not exist, the return
The return is null.

4. Judgment:
A Boolean isEmpty () length of 0 returns true otherwise false
Boolean ContainsKey (Object key) to determine whether the specified key is contained in the collection
Boolean Containsvalue (Object value) that determines whether the specified value is contained in the collection
5. Length:
Int size ()

Implementing Class HashMap (emphasis)

HashMap is not thread-safe, and if you want thread-safe hashmap, you can synchronizedmap get thread-safe HashMap by collections The static method of the class.

The bottom of the HashMap is primarily based on arrays, lists, and red-black trees, and it has a fairly fast query speed because it determines the location of the store by calculating the hash code. HashMap is mainly through the key hashcode to calculate the hash value, as long as hashcode the same, the calculated hash value is the same. If you store more objects, it is possible that different objects will have the same hash value, and there is the so-called hash conflict.

The specific method to look at the JDK document, it is recommended to look at its source code implementation, because HashMap later use a lot of, just know its few simple use method is far enough, but here is just simple cognition, I will not repeat, if can, later will out.

Implementing Class TreeMap

TreeMap is non-thread safe.
Thread safety can be obtained using the static method of the Collections class Synchronizedmap: Map m = collections.synchronizedsortedmap (new TreeMap (...));

TreeMap are sorted in ascending order by key. Sort by comparable or comparator. (Implementation and TreeSet are basically consistent).

The difference between HashMap and TreeMap
    1. Implementation method
      HASHMAP: Based on hash table implementation. The key classes you add with HashMap explicitly define hashcode () and Equals () [can override Hashcode () and Equals ()], and to optimize the use of hashmap space, you can tune the initial capacity and load factor.
      (1) HashMap (): Build an empty hash map image
      (2) HashMap (map m): Build a hash map image and add all the mappings for the images m
      (3) HashMap (int initialcapacity): Build an empty hash map image with a specific capacity
      (4) HashMap (int initialcapacity, float loadfactor): Constructs an empty hash map image with a specific capacity and load factor
      TREEMAP: Based on red-black tree. TreeMap has no tuning option because the tree is always in equilibrium.
      (1) TreeMap (): Building an empty image tree
      (2) TreeMap (Map m): Build an image tree and add all elements in image m
      (3) TreeMap (Comparator C): Build an image tree and sort the keywords using a specific comparer
      (4) TreeMap (SortedMap s): Build an image tree, add all the mappings in the image tree S, and sort with the same comparer as the ordered image s
    2. Use
      HashMap: Applies to inserting, deleting, and locating elements in a map.
      TREEMAP: For traversing keys (key) in natural order or in a custom order.
      HashMap is usually faster than treemap (the data structure of the tree and hash table), it is recommended to use HashMap, and TreeMap is used when the map needs to be sorted.

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.