Common methods and basic functions of Calendar class/Collection class/Math class/Regular expression/Array tool class in Java

Source: Internet
Author: User
Tags array length character classes dateformat repetition set set square root string format time in milliseconds

First, Arrays

For the tool class for array manipulation, some methods for array sorting and binary searching are provided.
Common methods:
1. public static string toString (Int[] a): Converts an array of type int to a string.
Converted to a string after the output form: ([element 1, Element 2, Element 3 ...]), arrays overrides the ToString method at the bottom.
2, public static void sort (int[] a): Sorts the specified array of type int in ascending order of numbers.
3, public static int BinarySearch (int[] a,int key): Binary search method, in array A to find the index of the key element. For example:

Second, Objectarray

An array of objects that stores an array of objects.
For example:

Third, System class

The System class contains some useful class fields and methods that cannot be instantiated.
Common methods:
1. public static void GC (): Runs the garbage collector. The essence is in the implementation of the Finalize method.
Override the Finalize () method in a custom class:

To run the GC method in a test class:

2. public static void exit (int status): Terminates the currently running Java virtual machine. parameter is a status code, to terminate the JVM, the parameter is 0.
Common status Code: 404 (HTTP status code, indicates that the requested page does not exist or has been deleted), 500 (server internal error), 200 (successful, indicates that the server completed the request successfully), 302 (further request).
3, public static Long Currenttimemillis (): Returns the current time in milliseconds.
The method used alone is meaningless and is typically used to test the execution efficiency of a piece of code.
4. public static void Arraycopy (Object Src,int srcpos, Object dest,int destpos, int length): Copies an array from the specified source array, starting at the specified position, Ends at the specified position in the destination array.
where SRC represents the original array, dest represents the target array, Srcpos indicates where to start from the original array, Destpos represents the end of the destination array, and length indicates the lengths.
For example:

Iv. Calendar class

1. Overview: The Calendar class, calendars class, is an abstract class.
2. Functions: (1) provides methods for conversion between a specific instant and a set of calendar fields such as year, MONTH, Day_of_month, HOUR, and (2) provides methods for manipulating calendar fields, such as getting the date of the next week.
3, instantiation method: public static Calendar getinstance (): A static function to create a calendar object, the method uses the default time zone and the locale to obtain a calendar, the calendar is returned based on the current time.
4, the Basic method:
(1) public int get (int field) returns the value of the given Calendar field.
(2) public static final int is year acquired.
(3) public static final int month gets months.
(4) public static final int DATE: Gets the day of the month.
5. Common methods:
(1) public abstract void Add (int field,int amount) Adds or subtracts a specified amount of time for a given calendar field based on a calendar rule. Common
(2) Public final void set (int year, int month,int date) Sets the value of the Calendar field year, month, and Day_of_month.
6, note: In obtaining the current date output month, you need to give the month +1 output.
For example:

V. Date class

1. Overview: Represents a specific moment, accurate to milliseconds.
2. Construction Method:
(1) Public date () indicates the time allotted to it (accurate to milliseconds).
(2) Public date (long date) creates a Date object that specifies the millisecond value. A long time millisecond value needs to be converted to a Date object.
(3) public void settime (long time) sets the millisecond value.
3. Common method: Public long GetTime () converts the Date object to a millisecond value of long time.
For example:

5. (emphasis) conversion between date and text formats
(1) Format: Date format (dates) → text format (String).
Method: Public Final String Format (date date)
(2) Parsing: Text Format (String) → date format (dates). (Note: SimpleDateFormat in parsing text format, the inside mode must be consistent with the text pattern, otherwise there will be an exception parseexception).
Method: Public Date Parse (String source)
(3) Intermediate conversion class: DateFormat. DateFormat is an abstract class that cannot be instantiated, so it should be instantiated using its subclass SimpleDateFormat.
(4) SimpleDateFormat, a specific class that formats and parses dates in a language-related manner, allowing formatting, parsing, and normalization. It is constructed by:
Public SimpleDateFormat (String pattern): Constructs a SimpleDateFormat object based on pattern (schema, rule). For example: SimpleDateFormat SDF = new SimpleDateFormat ("Yyyy-mm-dd")
(5) Date and time mode: Year (yyyy), month (mm), day (DD), Time (HH), Minute (MM), second (SS).
(6) For example:

(7) The tool class that dateutil:sting and date convert to each other.
For example:
Define Dateutil Features:

Converts a date to a string using the defined Dateutil function:

VI. Math class

1, Overview: Contains methods for performing basic mathematical operations, such as Elementary index, logarithm, square root and trigonometric functions.
2, JDK5 Features: Static import (the level of the import method).
3. Common methods:
(1) public static int abs (int a): absolute value
(2) public static double Ceil (double A): Rounding up
(3) public static double floor (double a): Rounding down
(4) public static int max (int a,int b): Max value
(5) public static int min (int a,int b): Minimum value
(6) public static double pow (double a,double b): Power of B of a
(7) public static double random () returns a random double value with a positive sign, range [0.0,1.0]
(8) public static int round (float a): rounded
(9) public static double sqrt (double A): a positive square root of a number
4, Bit ^ features: one data is another data bit ^ two times, its value is itself.
Common interview questions: with two variables A, B, using the method of bit ^, the value of the interchange:

Vii. Random Class

1. Overview: Gets the class of random number.
2. Construction Method:
(1) public Random (): No parameter construction method.
(2) public random (long Seed): Specifies a long type of data to construct a random number class object.
3. Common methods:
(1) public int nextint (): Gets the random number, range: Within the range of type int.
(2) public int nextint (int n): Gets the random number, range: [0,n].
4. For example:

Eight, regular expressions

1. Basic syntax:
(1) Characters:
A, x x characters
B, \ Backslash character
C, \ t tab
D, \ n line break
E, \ r return characters
(2) Character class:
A, [ABC] A, B or C
b, [^ABC] any character except A, B, or C (negation)
C, [a-za-z] A to Z or A to Z (range)
(3) Predefined character classes:
A. Any character, if it is ".", then ". "Write regular expression when writing" \. "
B, \d number [0-9], write "\d" when writing regular expressions
C, \w Word character: [a-za-z_0-9] (letter case, numeric character)
(4) Boundary matching device:
The beginning of a, ^ line
B, the end of the $ line
C, \b Word boundary/tail
(4) (emphasis) greedy quantity words
A, X? X not once or once
B, x* X 0 or more times
C, x+ X once or more
D, x{n} X characters happen to happen N times
E, X{n,} X characters appear at least n times
F, x{n,m} X characters appear at least n times, but not more than m times
2. Test method: public static Boolean matches (String regex)
Verifies that the input data matches the regular rule and returns true if the match succeeds.
For example: Enter a mobile phone number starting with 188, consisting of 11 characters:

3. Replacement method: public string ReplaceAll (string regex,string replacement)
Replaces this string with the given replacement for all substrings that match the given regular expression.
For example: Replace all numbers with "*":

4, String segmentation function: Public string[] Split (string regex)
Splits according to the specified format, and returns a string array after the split.
For example:

5. Pattern and Match typical call basic order
Common methods:
(1) public static pattern compile (String regex) compiles the given regular expression into the pattern
(2) The Matcher Matcher (String input) mode object is converted to a match object, that is, a matching object is constructed from the schema object.
For example:

Nine, Collection

1. Differences between arrays and sets (interview questions):
(1) Length: The array length is fixed and the set length is variable.
(2) Content: Arrays can store only elements of the same type, and collections store multiple types of elements.
(3) Storage type: An array can store a base type, or it can store reference types, and collections can only store reference types.
2, Overview: Collection, the root interface in the hierarchy. Collection represents a set of objects, also known as Collection elements. Some collection allow duplicate elements, while others do not. Some of the collection are orderly and some are unordered. is an abstract class and cannot be instantiated.
3. Instantiation: Collection c=new ArrayList ()
4, add the function:
(1) (Basic function) Boolean add (Object e) adds an element.
(2) (Advanced function) Boolean addall (Collection c) adds all the elements in a collection.
Boolean: Returns true as soon as it is added.
5. Delete function:
(1) (basic function) void clear (): Deletes all elements in the collection (brute force delete).
(2) (Basic function) Boolean remove (Object o): Removes the specified element from the collection.
(3) (Advanced function) Boolean RemoveAll (Collection c) deletes all the elements in a collection.
A, call: C1.removeall (C2), removes the elements from all C2 collections in C1.
B, Boolean: Returns True if an element is deleted, otherwise false.
6, including features:
(1) (basic function) whether the specified element is contained in a Boolean contains (Object O) collection.
(2) (Advanced function) Boolean containsall (Collection c)
A, call: C1.containsall (C2), C1 whether the collection contains all the elements in the C2 collection,
B, boolean:c1 must contain all elements in the C2 to return true.
7, get the function: (basic function) int size () The number of elements in the collection.
8. Intersection function: (Advanced function) Boolean retainall (Collection c)
(1) Call: C1.retainall (C2), C1 set to the C2 collection intersection, the intersection of the elements in the C1 collection.
(2) If the Boolean:c1 collection is changed, returns True if the change occurs, otherwise false is returned.
For example:

9. Conversion function: object[] ToArray () converts the collection to an array.
For example:

10. Collection proprietary traversal mode: Iterator traversal, Iterator Iterator ()

Ten, Iterator

1, set iterator method: Iterator Iterator (): Gets the iterator for the collection.
2, iterator interface common methods:
(1) Boolean hasnext (): Determines whether the next element can iterate, or False if it returns true.
(2) Object next (): Returns the next element of the iteration.
For example:

3. Common exception: Java.util.NoSuchElementException The exception occurs when no element is still acquired.
4. Precautions:
(1) It.next () generally only use once, if used more than once, prone to problems, it.next (), each use will return an object.
(2) When iterating through an iterator, you can use a while loop, or a for loop, where the while loop is a template code, often used, and for loops are seldom used.
5, the Itr:iterator class, an anonymous inner class.
6. Alternative iterators: Enhance the For loop.
7, collection two sub-interfaces: List,set
(1) List set features: Ordered (storage and extraction consistent), allowing the repetition of elements.
(2) Set Set features: unordered (not guaranteed based on iteration order, based on HashMap), and elements cannot be duplicated.

Xi. List

1, Characteristics: orderly (storage and removal of the same), allowing the repetition of elements.
2, Unique features:
(1) Add function: void add (int index,object Element) adds the specified element at the specified position.
(2) Get function: A, Object get (int index) returns the element at the specified position in the list.
B, Listiterator listiterator (): List iterator.
(3) Delete function: Object remove (int index): Deletes the element at the specified position.
(4) Modify function: Object set (int index, OBJECT element): Replaces the element at the specified position with the specified element.
3. List collection Proprietary iteration traversal: Listiterator listiterator ()
4, Listiterator interface Common methods:
(1) Boolean hasnext () determines whether there is an element that can be iterated (forward traversal).
(2) Object next () gets the next element.
(3) Boolean hasprevious () determines if there is an element that can iterate (reverse traversal).
(Backward traversal premise: there is already a forward traversal, using no meaning alone).
(4) Object Previous () returns the previous element.
5. The sub-implementation class of the list collection:
(1) ArrayList: The structure of the underlying data structure array, query block, adding and deleting slow. In terms of memory, threads are unsafe, unsynchronized, and highly efficient to perform.
(2) LinkedList: The structure of the underlying data structure linked list, slow query, adding and deleting blocks. In terms of memory, threads are unsafe, unsynchronized, and performing efficiently.
(3) Vector: Thread-safe class, the underlying data structure is an array, query fast, and delete slowly. In terms of memory, thread-safe, synchronous, inefficient execution.

Common methods and basic functions of Calendar class/Collection class/Math class/Regular expression/Array tool class in Java

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.