JAVA Study Notes (3) and java Study Notes

Source: Internet
Author: User
Tags time in milliseconds

JAVA Study Notes (3) and java Study Notes

@ SuppressWarnings ("resource") is used to suppress resource leakage warnings. For example, if I/O class is used, it is not closed.
Set features:
1) unordered, not random
2) unique element
3) No subscript
Note: Collection List Set is an interface
Note: Because the Set does not have a subscript, the value of for cannot be used, and only the iterator can be used.
HashSet: the internal structure is a hash table, so the elements are unique, unordered, and have no subscript.
TreeSet
.
LinkedHashSet: the internal structure is composed of a hash table and a linked list. Therefore, it is ordered and the elements are unique without subscripts.
HashSet:
HashSet <String> ss = new HashSet <String> ();
Ss. add ("");
Ss. add ("k ");
Ss. add ("d ");
Ss. add ("k ");

Iterator <String> its = ss. iterator ();
While (its. hasNext ()){
System. out. println (its. next ());
}

Result: unordered
LinkedHashSet:
LinkedHashSet <String> s = new LinkedHashSet <String> ();
S. add ("");
S. add ("g ");
S. add ("d ");
S. add ("g ");

Iterator <String> it = s. iterator ();
While (it. hasNext ()){
System. out. println (it. next ());
}
Result: a g d is ordered (retrieved in the stored order)

Map interface features: key and value appear in pairs.
Methods In the Map interface
1. Add V put (K key, V value)
2. Delete V remove (Object key)
Void clear ()
3. Judge boolean isEmpty ()
Boolean containsKey (Object key)
Boolean containsValue (Object value)
4. get V get (Object key)
Int size ()
Set <K> keySet ()
Map value
// No duplicates, no order, no subscript, no iteration, the value is displayed in pairs, and both the key and value can be empty (both can be empty). If the key is the same
Cap value
Map <String, String> map = new HashMap <String, String> ();
Map. put ("1", "aa ");
Map. put ("2", "bb ");
Map. put ("3", "cc ");
Map. put ("4", "ff ");
Map. put ("5", "ff ");
// Map. get ("5"); // one by one
Set <String> set = map. keySet (); // key is stored in the current set.
Iterator <String> it = set. iterator ();
While (it. hasNext ()){
String key = it. next ();
String value = map. get (key );
System. out. println ("key =" + key + ", value =" + value );
}
Differences between HashMap and HashTable
HashMap: The thread is insecure and fast. It can store null keys and null values.
Hashtable: thread security and slow speed. It cannot store null keys and null values. It has been replaced by HashMap.
TreeMap: sorts keys in the same way as TreeSet.

New For loop usage:
ArrayList <String> list = new ArrayList <String> ();
List. add ("");
List. add ("B ");
// 1) normal
For (int I = 0; I <list. size (); I ++ ){
System. out. println (list. get (I ));
}
// 2) enhanced
For (String temp: list)
{System. out. println (temp );
}
Note: 1) enhanced for should be used with generics
2) enhanced for has no subscript

Why is there a packaging class: It is convenient for us to operate on the data in the basic data type
Note:
Char (Character type) Character
Int (Integer) Integer
Other uppercase letters
Basic Data Type ------------ string
1) + String Connector
Int I = 1;
String str = I + "";
2) there are methods in String
String str2 = String. valueOf (I );
String ------- Basic Data Type
String str3 = "";
Int a = Integer. parseInt (str3 );
Note: The string must be a number; otherwise, NumberFormatException is returned.
Packaging class ------ Basic Data Type
Integer itsss = new Integer ("20 ");
Int age = itsss. intValue ();

Automatic packing and automatic unpacking
Previously: int m = 4;
Int n = 5;
Int B = m + n;
If: Integer m = new Integer (4 );
Int B = m. intValue () + 5; ---> after m is changed from the packaging class to the basic data type, + 5
Now: New features available after JDK
Integer p = 4; // automatic packing (convert the basic data type to the packaging class)
Int B = p + 5; // automatically unpack (the packaging class is converted to the basic data type)
List <Integer> list = new ArrayList <Integer> ();
List. add (1); // automatic packing (convert the basic data type to the packaging class)
Benefits: Easy programming.
Equals () method in the packaging class
The Wrapper class overrides the equals () method in the Object to compare whether the values are equal.
Integer a1 = new Integer ("20 ");
Integer a2 = new Integer (20 );
System. out. println (a1.equals (a2); // true

CompareTo () method in the packaging class
Public int compareTo (Integer anotherInteger)
Integer a1 = new Integer ("40 ");
Integer a2 = new Integer (30 );
System. out. println (a1.compareTo (a2 ));
A1 value = a2 value returns 0
A1 value <a2 value returns a negative number
A1> a2 returns a positive number.

Object Class: It is the root class of all classes. All methods in this class are inherited.
Equals and =
1) Comparison of basic data types:
3 = 3 true (compare value)
2) Comparison of objects:
New Person () = New Person () false (the memory address is compared)
3) object comparison:
New Person (). equals (New Person () false (the memory address is compared)
4) The equals in the String class overwrites the equals in the Object and compares the String content.
= Compare the address

HashCode
Return the hash value of the object:
New Person (). hashCode () --> the address of an int value 25860399 object is in decimal format
Integer. toHexString (25860399)-> 10 hexadecimal number to 16 hexadecimal number
Similar to a. ForTest @ 18a992f
The hash value is the object address value.
GetClass
Object Name. getClass (); get the package name and Class Name of the current object

ToString
ForTest f6 = new ForTest ();
System. out. println (f6); // f6 is equivalent to f6.toString (). It calls the toString () method in the Object class by default.
Note:
If toString () is rewritten in the ForTest class, System. out. println (f6); then the output value is the value in the rewrite method.
1) constant pool (directly assigned ):
String a = "abc"; --> Create a "abc" String in the pool
A = "bcd" ---> "Create in pool" String
A = "abc"; ---> use the "abc" string created in the pool
2) String a = new String ("aa"); ----> "aa" is not in the object in the pool.

Common Methods of the String class
1. Get the length of the string int length ()
2. Obtain the character char charAt (int index) based on the position)
3. Obtain the first position in the string based on the characters
Int indexOf (String str)
Int indexOf (String str, int fromIndex)
4. Obtain the first position in the string based on the characters
Int lastIndexOf (String str)
Int lastIndexOf (String str, int fromIndex)
5. Obtain a part of the string, also called a substring
String substring (int beginIndex)
String substring (int beginIndex, int endIndex) beginIndex-start index (including) endIndex-
End the index (not included ).
6. Conversion
1) convert a string to a string array (CUT)
String [] split (String regex), # space \.
2) convert string to character array
Char [] toCharArray ()
3) convert a string to a byte array
Byte [] getBytes ()
4) uppercase All characters in the string
String toUpperCase ()
5) lowercase All characters in the string
String toLowerCase ()
6) Replace the content in the string
String replace (char oldChar, char newChar)
7) Remove spaces at both ends of the string
String trim ()
8) string connection
String concat (String str)
9) convert the basic type to a string
Static String valueOf (Object obj) 100 to a String
7. Judgment
1) Compare string content:
Boolean equals (Object anObject)
2) Compare string content with uppercase and lowercase letters:
Boolean inclusignorecase (String anotherString)
3) whether the string contains the specified string
Boolean contains (String s)
4) Whether the string starts with the specified string and ends with the specified string
Boolean startsWith (String prefix) to test whether the String starts with the specified prefix.
Boolean endsWith (String suffix) test whether the String ends with the specified suffix (case sensitive)
8. Comparison
Int compareTo (String anotherString)

StringBuffer class
It is a string buffer, and the function of the string buffer is to facilitate the operation of the string
StringBuffer class features
1. Variable Length
2. Different types of data can be stored.
3. receive different types of data and convert it to a string for use.
StringBuffer sb = new StringBuffer ("aa ");
System. out. println (sb. toString ());
4. The string can be modified.
StringBuffer Constructor
StringBuffer sb = new StringBuffer (); the buffer is empty and the length is 0.
StringBuffer sb = new StringBuffer ("aa"); the buffer is not empty and the length is 2

StringBuffer Method
1. Add
StringBuffer append (boolean B)
StringBuffer insert (int offset, boolean B)
2. Delete
Public StringBuffer delete (int start, int end) does not include end
StringBuffer deleteCharAt (int index) deletes characters at a certain position
3. Search
Char charAt (int index) searches for characters at a certain position
Int indexOf (String str) searches for the subscript of a specified String
Int lastIndexOf (String str)
4. Modify
StringBuffer replace (int start, int end, String str) does not include end
Void setCharAt (int index, char ch)
5. Reverse
StringBuffer reverse ()
Finalize ()
Method called by the garbage collector before it is recycled. This method is generally used to release resources.
System. gc (): It is recommended that the Garbage Collector work. It is generally not used manually.
Math class
Static double ceil (double a) returns the smallest integer greater than the Parameter
Static double floor (double a) returns an integer smaller than the maximum value of the parameter.
Static int round (float a) Rounding
Static double pow (double a, double B) power B of
Static double random () returns a positive double value. The value is greater than or equal to 0.0 and less than 1.0.
System class
Returns the current time in milliseconds.
Static long currentTimeMillis ()
Static void exit (int status) terminates the currently running Java virtual machine. Status = 0 normal, 1 Abnormal exit
Static void gc () "suggested" to run the garbage collector.

Date
Current system time. Location in java. util package
Method:
New Date (); // The current time display format of the system is not in the Chinese format.
New Date (long date); // obtain the year, month, and day, in milliseconds
Long getTime () // get the current number of milliseconds
System. currentTimeMillis (); // get the current number of milliseconds
Note: conversions between date objects and milliseconds
1) date object-conversion ---- Ms
Date d = new Date ();
Long lo = d. getTime ();
2) millisecond -- convert ---- date object
Date d = new Date (lo );
DateFormat
The format time (the format style is fixed) is used in the java. text package.
This DateFormat is an abstract class and cannot be used to create objects.
Get the formatter:
DateFormat. getDateInstance (); this type of format is only for the year-month-day
DateFormat. getDateTimeInstance (); // year-month-day hour: minute: Second
DateFormat. getDateInstance (int parameter): // specify the style by Parameters
Example:
Date d = new Date ();
DateFormat df = DateFormat. getDateInstance (); // 2016-10-27 Thu Oct 27 10:57:57
CST 2016 ------ format ------->
String dateStr = df. format (d );
System. out. println (dateStr );

DateFormat df1 = DateFormat. getDateTimeInstance (); // 2016-10-27 10:36:38 Thu Oct
27 10:57:57 CST 2016 ------ format -------> 10:36:38
String dateStr1 = df1.format (d );
System. out. println (dateStr1 );

DateFormat df2 = DateFormat. getDateInstance (DateFormat. FULL); // October 27, 2016 star
Phase IV
String dateStr2 = df2.format (d );
System. out. println (dateStr2 );


DateFormat df3 = DateFormat. getDateInstance (DateFormat. LONG); // October 27, 2016
String dateStr3 = df3.format (d );
System. out. println (dateStr3 );

DateFormat df4 = DateFormat. getDateInstance (DateFormat. SHORT); // 16-10-27
String dateStr4 = df4.format (d );
System. out. println (dateStr4 );

DateFormat df5 = DateFormat. getDateInstance (DateFormat. MEDIUM); // 2016-10-27
String dateStr5 = df5.format (d );
System. out. println (dateStr5 );

SimpleDateFormat
The format time (the format style is customized) is used in the java. text package. Specify the format using parameters

Date d = new Date ();
SimpleDateFormat sdf = new SimpleDateFormat ("yy -- MM -- dd HH-mm-ss ");
String str = sdf. format (d );
System. out. println (str );
Result: 16--03--05 09-20-22

SimpleDateFormat sdf = new SimpleDateFormat ("yyyy-MM-dd hh: mm: ss ");
Date date = sdf. parse ("09:20:22 ");
Convert a Date of the string type to a Date of the Date type

Calendar
The calendar is in the java. util package.
Is an abstract class and cannot create objects,
Get calendar:
Calendar rightNow = Calendar. getInstance ();
System. out. println (rightNow );
Use the method in the calendar to obtain the value:
Int year = rightNow. get (Calendar. YEAR); // you can specify the year in the Calendar.
System. out. println (year );

Int month = rightNow. get (Calendar. MONTH); // the month in the Calendar starts from 0.
System. out. println (month );

Int date = rightNow. get (Calendar. DAY_OF_MONTH); // obtain the day 1 in the Calendar) DAY_OF_MONTH 2)
DATE is from 1, and the two parameters are the same
System. out. println (date );

Int weekday = rightNow. get (Calendar. DAY_OF_WEEK); // obtain the day of the week in the Calendar from Sunday.
It is counted as 4 in a week, that is, 5.
System. out. println (weekday );

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.