Java Study Notes (2)

Source: Internet
Author: User
Tags dateformat

1. Questions about date

Calendar theday = dateformat. getcalendar (); // This is the int thedayofweek = theday. get (calendar. day_of_week); // obtain the day of the week, Sunday, Monday, and so on.

② Date and calendar are two types. The former is a time class, focusing on time, only year, month, and day, without hour, minute, and second. The latter is a calendar class, focusing on time computing, with year, month, day, hour, and second. Convertible

// Convert calendar to datecalendar Cal = calendar. getinstance (); Date = Cal. gettime (); // convert date to calendardate date = new date (); Calendar ar Cal = calendar ar. getinstance (); Cal. settime (date );

③ Convert the string to Java. util. Date

Method 1: (commonly used)

Dateformat df = new simpledateformat ("yyyy-mm-dd"); Date d = DF. parse ("2005-2-19"); system. out. println (DF. format (d); // The output result is 2005-2-19.

Method 2:

Date D; dateformat df = dateformat. getdateinstance (); D = DF. parse ("2005-12-19"); system. out. println (d); // The output result is: Mon Dec 19 00:00:00 CST 2005system. out. println (DF. format (d); // The output result is 2005-2-19.

④ Format the output time (the most common method)

Date date = new Date();DateFormat dt = new SimpleFormatDate("yyyy-MM-dd hh:mm:ss");String time = dt.format(date);System.out.println(time);

⑤ How to obtain the current system time? There are three methods:

System. out. println (system. currenttimemillis); // This is the number of milliseconds that have elapsed since the Greenwich Mean Time origin (January 1, 1970, etc.) date d = new date (); // It is also the system time calendar c = calendar. getinstance (); // system time

Of course, you still need to format them.

Example:

Import Java. text. parseexception; import Java. text. simpledateformat; import Java. util. date; public class dateiodemo {public static void main (string [] ARGs) throws parseexception {date = new date (); // current time, current millisecond count // output yyyy-mm-dd hh: mm: SS simpledateformat FMt = new simpledateformat ("yyyy-mm-dd hh: mm: SS "); // format the date type as a time string STR = FMT. format (date); // format system. out. println (STR); // 2012-12-21 00:00:00 // parses the date string as the date type object string day = "2012-12-21"; simpledateformat F = new simpledateformat ("yyyy-mm-dd "); date d = f. parse (day); // parses the date string into milliseconds long l = D. gettime (); system. out. println (FMT. format (d); string S = new simpledateformat ("yyyy-mm-dd "). format (new date (); system. out. println (s); // 2012-04-18 }}

PS: simpledateformat class when formatting a string, you can call the format () or parse () function as needed, except that format () returns the string class and parse () returns Java. util. date class

2. parse () method of the dateformat class

The parse method is to convert a date of the string type to a date of the real date format. For example, "" can be seen as a date by the human eye, but for Java, it is only a string and it must be converted into a date type Java to know that this is a date.

3. About containers

① There are two interfaces in the collection of containers: Set and list. The data in the set cannot be duplicated in disorder, and the data in the list can be repeated in order. The data of hashmap in map is not ordered either.

② When using containers, add generics as much as possible to facilitate data storage and reading

③ When traversing containers, index traversal should be used as much as possible for list, And iterator should be used for set as much as possible

④ Iterator, which can iterate both list and set

⑤ All the container classes that implement the collection interface have an iterator method to return the objects that implement the iterator interface. The iterator object is called an iterator used to traverse elements in the container. This method can iterate both the list and set

 

Example: traversal of list, set, and map sets

 

/*** Test the traversal operation on the list, set, and map sets. * when traversing the container, the list should be traversed using indexes as much as possible. The set uses the iterator **/package COM. bjsxt. test. collection; import Java. util. arraylist; import Java. util. collection; import Java. util. hashmap; import Java. util. hashset; import Java. util. iterator; import Java. util. list; import Java. util. map; import Java. util. map. entry; import Java. util. set; public class testpractice {public static void testlist () {list <student> List = new arraylist <student> (); list. add (new student ("James"); list. add (new student ("Li Si"); list. add (new student (""); // index traversal for (INT I = 0; I <list. size (); I ++) {student Stu = List. get (I); system. out. println (Stu. getname ();} // use an enhanced for loop, which is essentially an index traversal for (student STU: List) {system. out. println (Stu. getname (); // This is simpler than the above} // use the iterator <student> iter1 = List. iterator (); While (iter1.hasnext () {// This is used to determine whether an element has been traversed. // the return value of next () is of the object type, you need to convert it to another type of student Stu = iter1.next (); // return the current element and point the cursor to the next system. out. println (Stu. getname ();} // or use the following method for (iterator <student> iter2 = List. iterator (); iter2.hasnext ();) {// the third sentence in for (that is, the next line), that is, student Stu = iter2.next (); system. out. println (Stu. getname () ;}} public static void testset () {set <student> set = new hashset <student> (); set. add (new student ("James"); set. add (new student ("Li Si"); set. add (new student (""); // use the enhanced for to index and traverse for (student STU: Set) {system. out. println (Stu. getname ();} // use the iterator <student> iter2 = set. iterator (); While (iter2.hasnext () {student Stu = iter2.next (); system. out. println (Stu. getname () ;}// it is troublesome to traverse the map. Use entrypublic static void testmap () {Map <string, student> map = new hashmap <string, student> (); map. put ("A", new student ("001"); map. put ("B", new student ("002"); map. put ("C", new student ("003"); // traverses keyset <string> set1 = map. keyset (); // set an instance iterator <string> iter1 = set1.iterator (); While (iter1.hasnext () {string STR = iter1.next (); system. out. println (STR + "----" + map. get (STR ). getname ();} // traverse valuecollection <student> set2 = map. values (); iterator <student> iter2 = set2.iterator (); While (iter2.hasnext () {student Stu = iter2.next (); system. out. println (Stu. getname ();} // traverses the key-Value Pair entryset <entry <string, student> set3 = map. entryset (); iterator <entry <string, student> iter3 = set3.iterator (); While (iter3.hasnext () {entry <string, student> V = iter3.next (); system. out. println (v. getkey () + "-----" + v. getvalue () ;}} public static void main (string [] ARGs) {testlist (); testset (); testmap ();}}


4. Exceptions

① If there is a parent-child relationship between multiple exceptions, first put the child class and then put the parent class!
② If there is finally in the exception, the code in finally will be executed no matter whether there is any exception!
③ Common methods for catch exceptions:
Tostring () method: The Class Name of the actual exception and the cause of the exception
Getmessage () method: only the cause of the exception is displayed, but the class name is not realistic.
Printstacktrace (): used to track the stack content when an exception event occurs.

5. Add some polymorphism, such:

Collection c = new arraylist ();
The parent class references the subclass object, which is a manifestation of polymorphism, but the parent class cannot access the member variables of the subclass. If you want to change other methods in the future, you can simply replace arraylist, which is very convenient. If you write
Arraylist c = new arraylist (); it is very troublesome to replace it with other methods.


6. Supplement:
Functions of the tostirng method in the object class
A. in the object class, return is defined by default: class name + hash code (corresponding address)
B. When printing an object, the tostring method is called by default to print the string returned by the method (that is, the class name and corresponding address)

7. In an exception, if return and finally exist, return returns the value first, then run finally, and then end the operation. All in all, the finally statement is executed. In addition, it is best not to write the return statement in the finally statement block. For example:

Import Java. io. filenotfoundexception; import Java. io. filereader; import Java. io. ioexception; public class test03 {public static void main (string [] ARGs) {string STR = new test03 (). openfile (); system. out. println (STR);} string openfile () {try {system. out. println ("AAA"); filereader FCM = new filereader ("D:/ad.txt"); // checked !!! Int A = FCM. Read (); system. Out. println ("BBB"); // determine the returned value and the operation will not end directly! Return "Step1";} catch (filenotfoundexception e) {system. Out. println ("catching !!!! "); E. printstacktrace (); Return" step2 "; // determine the returned value and the operation will not end directly !} Catch (ioexception e) {e. printstacktrace (); Return "Step3" ;}finally {system. Out. println ("Finally !!!! "); // Return" fff "; // do not use return!} In finally !}}}

The running result is:

Aaaaahahahjava. Io. filenotfoundexception: D: \ a .txt (the system cannot find the specified file .) At java. io. fileinputstream. open (native method) at java. io. fileinputstream. <init> (fileinputstream. java: 138) at java. io. fileinputstream. <init> (fileinputstream. java: 97) at java. io. filereader. <init> (filereader. java: 58) at com. bjsxt. test. exception. test03.openfile (test03.java: 16) at com. bjsxt. test. exception. test03.main (test03.java: 9) finallystep2

It can be seen from the above that the finally statement is executed first, and then step 2 is returned to end the operation.

8. Manually throw an exception that is inherited from runtimeexception and does not require try/catch.

9. In the map container, in the <key, value> attribute, the key must be a packaging class.

Map <integer, student> map = new hashmap <integer, student> (); // use Map <string, student> map = new hashmap <string, student> (); // use Map <int, student> map = new hashmap <int, student> (); // report an error

10. stream classification
① Input stream and output stream by Flow Direction
② Streams are divided into byte streams (ending with stream) and bytes streams (reader and writer) by transmission unit)
Bufferedreader and bufferedwriter are character buffer streams. The special method is Readline () to read a text line, and newline is writer to the next text line.
To increase the speed, you can use the cache, which is essentially an array.

Byte [] buffer = new byte [1024] // 1024 can be replaced with other values

11. Some basic stream Methods

First, ha: 1 character = 2 bytes


① Inputstream

Int read () // read a byte and return it as an integer. If-1 is returned, it indicates it has reached the end of the input stream.

② Outputstream

Void write (int x) // write a byte of data to the output stream void flush () // write the buffer data of the output stream to the destination

③ Writer

Void write (int x) // write a character data void write (string Str) to the output stream // write the characters in a string to the output stream void flush () // write all the data in the output stream to the destination

④ Reader

Int read () // read a character and return it as an integer. If-1 is returned, byte [] buffer = new byte [1024] is reached the end of the input stream. // The cache mechanism int Len = 0; // The length of the received data is read cyclically while (stream. read (buffer )! = Len )! =-1)

⑥ Conversion stream

The function is to convert byte streams into bytes streams, which are used in many places.

Inputstreamreader needs to be nested with inputstream

Outputstreamwriter needs to be nested with outputstream

For example:


Stream summary:

12. supplement

Variable is static binding, and the method is dynamic binding. For example:

Public abstract class car {string type; Public void run () {system. out. println ("car ..... ");} public car () {} public void GetType () {system. out. println (type);} public static void main (string [] ARGs) {car = new BMW (); car. type = "car"; car. run (); // a multi-state car occurs. getType (); // The value is null, not car} class BMW extends car {string type; Public void run () {system. out. println ("........ ") ;}Public void GetType () {system. Out. println (type );}}

The output result is ........ And null
Because the variable is static binding, the method is dynamic binding. Static binding refers to the type of the variable itself, which is used. For example, if car. type is of the car type, type is inside the car. The method is inside the subclass BMW. Static binding can also be understood as the Java command generation. Class file, dynamic binding to run Java programs.

13. About threads

① The sleep method called in the thread will sleep the thread.

② Runnable has only one public void run () method to define the thread runtime body.

③ Differences between wait and sleep Methods
There is a big difference between the two. The wait method belongs to the object class, and sleep belongs to the Thread class. Both can pause a process, but other threads can also access the locked object during wait. During sleep, other threads cannot access the locked object.

14. Add some object-oriented things:

The relationship between interfaces is extends. An interface can inherit multiple interfaces.
The relationship between classes and interfaces is implements. A class can inherit multiple interfaces.
The relationship between classes is inheritance. A class can only inherit one class.


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.