Java Classic Usage Summary (ii) _java

Source: Internet
Author: User

Then we will introduce Java applications and input and output methods commonly used for your reference, the specific contents are as follows

First, the application

1. Use StringBuilder or StringBuffer

Join (["A", "B", "C"])-> "A and B and C"

String join (list<string> strs) {

 StringBuilder sb = new Strin Gbuilder ();

 Boolean-i = true;

 for (String s:strs) {

 if (a): false;

 Else Sb.append ("and");

 Sb.append (s);

 }

 return sb.tostring ();

}

    • Do not use duplicate string concatenation like this: s + = Item, because its time efficiency is O (n^2).
    • When using StringBuilder or StringBuffer, you can use the Append () method to add text and use the ToString () method to get the entire text connected.
    • Prioritize the use of StringBuilder because it's faster. All methods of StringBuffer are synchronized, and you usually do not need to synchronize the methods.

2, generate a range of random integers

Random rand = new Random ();

 

Between 1 and 6, inclusive

int diceroll () {return

 Rand.nextint (6) + 1;

}

    • Always use the Java API method to generate a random number in the range of integers.
    • Do not attempt to use Math.Abs (Rand.nextint ())% n These indeterminate uses, because the result is biased. In addition, its result value may be negative, such as when rand.nextint () = = Integer.min_value.

3. Use Iterator.remove ()

void filter (List<string> List) {for

 (iterator<string> iter = List.iterator (); Iter.hasnext ();) {

 String item = Iter.next ();

 if (...)

  Iter.remove ();

 }



The Remove () method acts on the item that is recently returned by the next () method. You can only use the Remove () method once per entry.

4. Back-turn string

String reverse (string s) {return

 new StringBuilder (s). Reverse (). toString ();

}

This method might be added to the Java Standard library.

5. Start a thread
The following three examples use different ways to accomplish the same thing.

Ways to achieve runnnable:

void StartAThread0 () {

 new Thread (New Myrunnable ()). Start ();

 

Class Myrunnable implements Runnable {public

 void run () {

 ...}}

}

How to inherit thread:

void StartAThread1 () {

 new Mythread (). Start ();

 

Class Mythread extends Thread {public

 void run () {

 ...}}

}

How to inherit thread anonymously:

void StartAThread2 () {

 new Thread () {public

 void run () {

  ...}}

 }. Start ();

}

Do not call the run () method directly. Always call the Thread.Start () method, which creates a new thread and makes the new thread call run ().

6. Use try-finally
I/O Flow example:

void Writestuff () throws IOException {

 OutputStream out = new FileOutputStream (...);

 try {

 out.write (...);

 } finally {

 out.close ();

}}

Lock Example:

void Dowithlock (Lock lock) {

 lock.acquire ();

 try {

 ...

 } finally {

 lock.release ();}

}

    • If the statement before the try fails and throws an exception, then the finally statement block is not executed. But no matter what, in this case there is no need to worry about the release of resources.
    • If the statement in the try statement block throws an exception, the execution of the program jumps to the finally statement block to execute as many statements as possible, and then jumps out of the method (unless the method has a finally block of another peripheral).

Second, the input/output

1. Read byte data from input stream

InputStream in = (...);

try {while

 (true) {

 int b = In.read ();

 if (b = = 1) break

  ;

 (.... process B..)}}

finally {

 in.close ();

}

The read () method either returns the next number of bytes read from the stream (0 to 255, including 0 and 255), or returns-1 when the end of the stream is reached.

2. Read block data from input stream

InputStream in = (...);

try {

 byte[] buf = new byte[100];

 while (true) {

 int n = in.read (BUF);

 if (n = = 1) break

  ;

 (... process buf with offset=0 and length=n ...)

 }}

finally {

 in.close ();

}

Keep in mind that the read () method does not necessarily fill the entire buf, so you must consider the length of the return in the processing logic.

3, read the text from the file

BufferedReader in = new BufferedReader (new

 inputstreamreader (...), "UTF-8");

try {while

 (true) {

 String line = In.readline ();

 if (line = = null) break

  ;

 (.... Process line ...)

 }}

finally {

 in.close ();

}

    • The creation of BufferedReader objects is tedious. This is because Java looks at the byte and the character as two different concepts (this is different from the C language).
    • You can use any type of InputStream to replace FileInputStream, such as sockets.
    • Bufferedreader.readline () returns NULL when the end of the stream is reached.
    • To read one character at a time, use the Reader.read () method.
    • You can use other character encodings without using UTF-8, but it's best not to do so.

4. Write text to the document

PrintWriter out = new PrintWriter (new

 outputstreamwriter (...), "UTF-8"));

try {

 out.print ("Hello");

 Out.print (a);

 Out.println ("world!");

} finally {

 out.close ();

}

    • The creation of PrintWriter objects is tedious. This is because Java looks at the byte and the character as two different concepts (this is different from the C language).
    • Like System.out, you can print multiple types of values using print () and println ().
    • You can use other character encodings without using UTF-8, but it's best not to do so.

The above is the entire content of this article, I hope to help you learn.

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.