Common Java arrays, strings, set operations, and basic knowledge of data structures and algorithms

Source: Internet
Author: User
Tags array length array to string in degrees

In Java commonly used encapsulated arrays, strings, sets to manipulate objects, but the data structure commonly used in the stack and the number of queues and graphs and the sort between them, find.

An array declaration does not allocate memory space until it is created or initialized, assigning the first address of the data type data in the array to the array name, and assigning an address and the data it stores when each object is created. such as variable int arr[];  int arr[]={1,2,3}; Arr=new int[10], int arr[][]={{1,9,7},{1,2,3}} int arr[][]=new int[7][10]

Default value

Integral type: 0

Real: 0.0f or 0.0d

Character type: ' + ' or ' \u0000 '

String: null

Common operations: Length array ToCharArray () string to character array valueof (char[]) character array to string as new String=new string (char[])

string

A string of new string ("str") can be created at the same time as two objects, one is a string constant pool, and the other is a string object. String constants in the pool are no longer created

Length () string size parseint (string s) string to int type valueof (int i) int type to String Intvalue () is to convert integer to int new integer (int v Alue) or valueof (int value) to convert int to an integer object

New String (char[])

New String (string s)

New String (StringBuffer SB)

New String (byte b[])

New String (Byte b[],offset,int count)

NET string (Str.getbytes (String utf-8), string GBK);

Method

Equals (String s)

Equlsignorecase (String s)

StartsWith (String s)

EndsWith (String s)

CompareTo (String s)

IndexOf (String s)

LastIndexOf (String s)

charAt (int index)

Concat (String str)

ToCharArray ()

ToString ()

toUpperCase ()

toLowerCase ()

Trim ()

Split (String regex)

IsEmpty ()

subString (int start,int end)

Replace (String new,replace old)

GetBytes (String utf-8)

String constants are treated as strings and cannot be modified, deleted, replaced by a character in a string constant, and StringBuffer is treated with a string variable whose value and length can be modified.

New StringBuffer () default length is 16 bytes

New StringBuffer (int length) Setting object initial capacity is length byte

New StringBuffer (String str) length is str length + 16 bytes

Method

Append (String s)

charAt (int n)

Setcharat (int N,char ch)

Insert (int index,string str)

Reverse ()

Delete (int start,int end)

replace (int start,int end,string str)

There are other commonly used class system. Math Random Date

Collection

Judging the different types of collections is mainly from thread-safe, orderly, repetitive

List, set are inherited the collection interface list is ordered, repeatable. Collections is a class that has a variety of static methods for manipulating collections.

Map is a key-value class: Stored as a key-value pair, key is unique, but value can be duplicated.

List of commonly used subclasses: vector, ArrayList difference is vector is synchronous, LinkedList linked list to add or delete data without a lot of mobile data.

Map commonly used subclasses: hashTable, TreeSet difference is hashTable is thread-safe, synchronous but does not allow key or value is NULL with enumeration er=new Hashtable.keys (); Er.hasmoreelements ();. Get (Er.nextelement (), and HashMap with iterators.

Set commonly used subclasses: TreeSet Two The binary tree is ordered HashSet is unordered, which means that the input data is inconsistent with the output data order.


In Java, a hash code represents a characteristic of an object, such as we determine whether a string is = =, and if its hash code is equal, the two strings are equal. Secondly, hash code is an algorithm of data structure. Common hash code algorithms are:
The hashcode of the 1:object class. Returns the memory address of the object after the processing of the structure, because each object's memory address is different, so the hash code is not the same.
The hashcode of the 2:string class. Based on the contents of the string contained in the strings class, the hash code is returned according to a special algorithm, and the hash code returned is the same as long as the string contents are the same.
In the 3:integer class, the hash code returned is the numeric value of the integer contained in the integer object, such as the integer I1=new integer, and the value of I1.hashcode is 100. This shows that 2 of the same size of the integer object, the same hash code returned

Method:

Remove (Object obj)

Add (Object obj)

AddAll (Collection c)

Iterator ()

Contains (Object obj)

Containsall (Collection c)

Clear ()

Hashcode ()

Equals (Object obj)

IsEmpty ()

Size ()

Map interface method

Put (Key,value)

Get (Object key)

Remove (Object key)

ContainsKey (Object key)

Containsvalue (Object value)

Note: = = differs from equals (Object obj), = = is the value comparison in the base data type, and the other is the address comparison. equals compares the content when a string Integer date overrides the Equals method, and the other compares the memory address.

Data Structure

Data: What are the attributes of the object (node), using the constructor to pass the attribute in, or setxx the method into the set, using the Getxx method to remove the attribute.

Relationship: What is the relationship between objects.

Operation: Create, add, delete, change, check, platoon.

A pointer in C is equivalent to an object reference in Java, a reference to a property that can call it, a variable, and a function. The first new object instance that gets is the head node.

Linked list:

Linear lists: Nodes consist of a data field and a pointer field where the pointer field stores a reference to the next object.

Create classes or interfaces (encapsulate objects with the same class attributes into classes)

Interface class linknode{

Object obj;//Data Objects

Linknode next;//Hands

Public Linknode ()

{

This. Linknode (Null,null);

}

Public Linknode (Object Obj,linknode next) {

This.obj=obj;

This.next=next;

}

Private Setnext (Linknode next) {
This.next=next;}

Private GetNext () {

return next;

}

Private Setobj (Object obj) {

This.obj=obj;

}

Private Getobj () {

return obj;

}

}

Insert Method:

Problem: To insert a data element (node) x between the two data elements (nodes) A and B of a linear table,

function: Inserting an element at a location

Parameters: Data element, location

return value: None

Logic: The pointer field of the precursor of the I position (that is, the B node) is first found, that is, the reference of B, the next in the attribute of a, assigns it to the new node, and then new comes out the reference of the node, assigns a value to a

Modification Time:

Creation time:

void Insert (Object obj,int i) throws exception{

if (i>size| | I<0)

throw new Exception ("unreasonable input position");

try{

Linknode head;//head pointer or head node (data field is the linked list length)

Linknode p=head;//Traversal pointer

while (P!=null)

{if (p.data==b)

Return P

Assignment operation

{

Linnode q=new Linknode (Obj,p.getnext ())//assigns the pointer field value of the precursor node to the new node.

P.setnext (q);

Else

p=p.next;//traversal

}

Return

}


Circular link list:

The other is the same as the linear list, the difference is that the last node points to the head node, so determine whether to the last node, can be used to point to the head node.

Relationship

Operation

Doubly linked list: Unlike linear lists, each object is incremented with a post-precursor pointer field


Stack

The rule is advanced after the pointer is traversed to the bottom of the stack when the cursor field is a null object only after the drive pointer field and the data field without a head node with a head pointer can be stored sequentially with overflow overflow

Storage structure linked lists and arrays

Logical Structure linearity

The application of syntactic lexical analysis to the evaluation of the value conversion of expressions

Queue

Rules advanced first out there are team head front allow insertion of the team tail rear allow to delete the boss pointer and the tail pointer to the same position when the queue is empty regardless of whether the incoming team or the team tail pointer is to move the high address out of the team move the head pointer into the team moving tail pointer in order to false overflow using circular queue header tail finger When the pin points to the highest address, the incoming team overflows, but the low address has room to return to the low address with the loop queue and back into the queue.

Storage structure linked lists and arrays

Storage structure

Application of CPU time- sharing system to simulate printer buffer Bank queuing

tree with two fork tree

A large number of input data, linear table access time is too slow, not suitable for use.

Basic Tree Concepts

(1) Tree concept: The tree is a recursive definition of the data structure, is an important non-linear data structure. A tree can be an empty tree, it has no nodes, or it can be a non-empty tree with at least one node.
(2) root (root): A non-empty tree with only one node, which is the root.
(3) Sub-tree (subtree): In a non-empty tree, root, all the remaining nodes can be divided into m (m≥0) disjoint collection. Each set is itself a tree, called the root subtree.
(4) Node: Represents an element in a tree and several branches that point to its subtree.
(5) The degree of the node (degree): The number of subtrees owned by a node is called the degree of the node.
(6) leaf node (leaf): A node with a degree of 0.
(7) Child: The root of the knot point tree is called the child of the node.
(8) Parents (parents): The upper node of the child's knot is called the parent of the node.
(9) Brothers (Sibling): Children of the same parents.
(10) The degree of the tree: the maximum number of nodes in a tree.
(11) The level of the node: define the root as the first layer from the root node, its child is the second layer, and so on.
(12) Depth (Depth): The value of the maximum level of nodes in the tree. The root node is a layer, and the leaf knot is a layer.
(13) Ordered tree: Each subtree in the tree is ordered from left to right, which is called ordered tree.
(14) Unordered tree: Each subtree in the tree is unordered from left to right, which is called unordered tree.
(15) Forest (Forest): A collection of M (m≥0) disjoint trees.
(16) Ancestor: Refers to all the nodes from the root node to the node.

Full two fork tree: all nodes on each layer have two sub-nodes two fork trees, except for the last layer without any subnodes. A total of 2^k-1 nodes.

Complete binary tree: its node order corresponds to a tree of two forks. If the depth of the two-fork tree is H, except for the H layer, the nodes of each layer (1~H-1) reach the maximum number, and all nodes of the H layer are continuously concentrated on the leftmost side, which is the complete binary tree.

Storage structure

Binary Tree Traversal

(1) Sequential traversal (first root traversal)
1. Access root node
2. First Order traversal Zuozi
3. First-order traversal of the right sub-tree
(2) Middle sequence traversal (middle root traversal)
1. Middle Sequence Traversal Zuozi
2. Access root node
3. The middle sequence traverses the right sub-tree
(3) Sequential traversal (post-root traversal)
1. Post-Zuozi traversal
2. Post-the-loop traversal of right sub-tree
3. Access root node

Clue Two fork Tree

Optimal binary tree (Huffman tree): The length of the node-weighted path is the product of the path length between the node and the root, and the length of the tree's weighted path is the sum of the weighted path length of all the leaf nodes in the tree. Assuming that there are n weights, try to construct a two-fork tree of n leaf nodes, each with the corresponding weights, the two-tree with the minimum length of the weighted path is the optimal binary tree or Huffman tree.

Constructing Huffman Tree Process

(1) According to a given n weights of the keywords, constitute a set, in the set of two weights to find the smallest of the new weights, until with the last weight to form a new weight value. (new weights correspond to new nodes with no keywords)

Apply Havermann Encoding

Figure

Any two vertices may have a relationship

Basic concepts of graphs

No map: There is no direction for each edge of the graph;
Directed graphs: Each side of the graph has a direction;
No edge: The Edge is no direction, write as (A, B)
Forward Edge: Side is directional, write as <a,b>
Having an edge also becomes an arc; the beginning vertex is called the arc tail, and the ending vertex is called the arc head;
Simple diagram: There is no diagram pointing to its own edge, there is no two duplicate edges;
Non-direction full graph: There is an 1/2n (n-1) edge of an anisotropic graph with one edge between each vertex;
Forward full graph: There are two opposite edges of each vertex with n (n-1) edges;
Sparse graphs: graphs with few edges relative to vertices;
Dense graphs: A lot of graphs on the side;
Weight: The edges in the graph may have a weight, in order to distinguish the length of the edges;
NET: a graph with weights;
Degree: The number of edges connected to a particular vertex;
Out degrees, degrees: for the concept of a graph, the number of edges that this vertex is the starting point, and the number of edges that this vertex is the end point, in degrees;
Path: The length of the path is the number of edges or arcs on the path, and the paths of vertices that are not duplicates in the sequence are called simple paths
Ring: The same path as the first vertex and the last vertex;
Simple ring: A ring with no repeating vertices after the first vertex and the last vertex are removed;
Connect graph: Any two vertices are connected to each other diagram;
Maximal connectivity sub-graph: Contains possibly many vertices (must be connected), that is, cannot find another vertex, so that this vertex can connect to any vertex of this maximal connectivity sub-graph;
Connected components: The number of maximal connected sub-graphs;
Strong connectivity diagram: This is the concept of a forward graph, representing any two vertices, a, a, so that a can be connected to the B,b can also be connected to a diagram;
Spanning Tree: n vertices, n-1 edges, and ensuring that n vertices are interconnected (no loops);
Minimum spanning tree: the sum of the weights of the edges of this tree is the smallest of all spanning trees;
AOV Network: node represents the activity of the net, should not appear to have a ring;
AOE Net: The net of the duration of the activity;


Storage structure of graphs

Adjacency Matrix

adjacency table

Cross linked list

Array of Edge Sets

Adjacency multiple table


The traversal of graphs

Depth-First search: a vertex that accesses this vertex, and then sequentially from the adjacency point to which the vertex is not visited, takes a deep precedence over the graph until all vertices with a path to the vertex are accessed, and if there are vertices in the graph that are not accessed, a non-visited vertex in the diagram is used as the starting point, repeating the process, Until all vertices in the graph have been accessed.

Breadth-First search: a vertex that accesses this vertex, and then sequentially from the adjacency point to which the vertex is not visited, takes the breadth-first traversal of the graph until all the vertices in the diagram that have a path to the vertex are accessed; if there are vertices in the graph that are not accessed, a non-visited vertex in the diagram is used as the starting point Until all vertices in the graph have been accessed. Note that the next layer of the same layer is the same as the top-level adjacency point is to be accessed in turn, such as the left node of the next layer of adjacency point access to the next level of the right node to access the adjacency point.

Minimum spanning tree: in n vertices, the most edges in the graph have n (n-1), while the connected n vertices require a minimum of n-1 edges, assuming that there is a right value on the edge, you need to select the lowest-cost n-1 edge from the N (n-1) edge according to the premium Manaus algorithm or Kruskal algorithm to form the spanning tree.

Topological ordering: can determine whether there is a forward ring in the network, select a vertex without a precursor in the graph, and output it, delete the vertex and all the arcs with its tail, repeat the above two steps, until all vertices have been output, it is described as a non-circular graph.

Critical path: The longest path from the source point to the end point is called the critical path, the vertex is called the event, and the edge is called the activity. The earliest time the event started, the latest event that started the event

Shortest path: The shortest path is the minimum length of the source point to a point.

Heap (Dynamic storage management)

Sort

To view http://blog.jobbole.com/11745/


Merge sort: A length of n array adjacent to the length of 1 sub-sequence to merge, get N/2 length of 2 or 2 of the sub-sequence, and then merge adjacent sub-sequence 22, repeated execution until there is only one sequence

Select Sort: Select the largest from an array, followed by the previous interchange (without defining a new array, the flag flag is the smallest), you need to exchange n times

Heap sort: The unordered array is built into a heap, the first element of the array begins to do the root node, the next two elements do the left and right child nodes, two child nodes and then the next 4 elements as children node, until the array elements are used up; then output heap top (heap top for the largest heap of large top, sort to small, the smallest is the small top heap, small to large sort), then the heap top element with the last element exchange (the bottom of the complete binary tree, from the right side of the node), then the heap is destroyed, re-build the heap, and then output the heap top, and then rebuild ...

Insert sort: From an array of first thought ordered, followed by the elements inserted into the appropriate position in the order Arr[j+1]=arr[j];(so to move the element)

Hill Sort:

Quick sort: From the first element in an array as a keyword, starting with the last element compared to it, swapping it smaller than it, and then comparing it with the second element, and then comparing it with a third element compared to it. After the first trip is divided into the keyword position for the identification, it is later than the sequence is larger than the previous sequence, the preceding sequence as a new sequence, re-follow the previous row, followed by the same sequence, so can be recursive until i>=j (i is the preceding array increment subscript 0 J is after Polygon Array Decrement Subscript array Length-1)

Bubble sort: The first record is compared with the adjacent record, then the position is compared with the next adjacent record, and the largest record is the last one (small to large).

Base sort

Time complexity (average):

Direct insert, direct selection, and bubble sort to (O (n^2)) squared

Quick sort, heap sort, and merge sort to (O (nlog2n))

Stability (the same record is, whether moving, moving is not stable):

Stable sorting algorithms: bubble sort, insert sort, merge sort, and Cardinal sort

Unstable sorting algorithm: Select sort, quick sort, hill sort, heap sort

Algorithms to handle big data sorting: fast sorting, heap sorting, merge sorting

Small amount of data use sorting algorithm: Insert sort, select sort

Note: When the original table is ordered or basically ordered, the direct insertion of sort and bubble sort will greatly reduce the number of comparisons and moves, the time complexity can be reduced to O (n), while the quick sort is the opposite, when the original table is basically ordered, it will become a bubble sort, the time complexity is increased to O (N2).

Find

Static lookup: The data in the lookup table does not change

Ordered: Search by binary (same as the probability of each record in the table) or suboptimal find tree

Unordered: Sequential Lookup

Index Table: Two-tier table, the first layer using binary to find the second layer in order to store so in order to find

Dynamic find: Find the process data in the lookup table is a change, there is a delete or insert operation

Binary sort tree: The structure of a tree is usually not generated at once, but in the process of finding it, inserting it when there is no keyword equal to the given node in the tree. The characteristic is that the root node is larger than the left child, smaller than the right child. You can modify the pointer based on the node location when you delete the data. Find with Binary. The number of lookups for a two-tree does not exceed its depth.

Balanced binary tree: its left and right sub-trees are balanced binary trees, and the Zuozi of the difference between the depth of the tree is not more than 1 absolute value. The equilibrium factor is the value of the right subtree of the node in which the left subtree goes into the node, so only for 1,0,-1, so that the two-fork sort tree satisfies the equilibrium binary tree needs to use the balance factor to make the judgment, does not satisfy on the rotation makes the final satisfaction. Find the same as the two-fork sort tree (binary lookup tree), but they are all equal probabilities.

B-and B + trees: There is also a series of sorted data on the nodes.

Hash table: Array vs. keyword hash functions and handling conflict methods


Some of the content is not very full and there are many algorithmic code is not given, the future slowly add!


Common Java arrays, strings, set operations, and basic knowledge of data structures and algorithms

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.