In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces the relevant knowledge of "what is the use of Java". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Implement equals ()
Class Person {String name; int birthYear; byte [] raw; public boolean equals (Object obj) {if (! obj instanceof Person) return false; Person other = (Person) obj; return name.equals (other.name) & & birthYear = = other.birthYear & & Arrays.equals (raw, other.raw);} public int hashCode () {...}}
The parameter must be of type Object, not a peripheral class.
Foo.equals (null) must return false and cannot throw NullPointerException. (note that any null instanceof class always returns false, so the above code can run.)
The comparison of primitive type fields (for example, int) uses = =, and the comparison of primitive type array fields uses Arrays.equals ().
When overriding equals (), remember to override hashCode () accordingly, consistent with equals ().
Reference: java.lang.Object.equals (Object).
Implement hashCode ()
Class Person {String a; Object b; byte c; int [] d; public int hashCode () {return a.hashCode () + b.hashCode () + c + Arrays.hashCode (d);} public boolean equals (Object o) {.}}
When the x and y objects have x.equals (y) = = true, you have to make sure that x.hashCode () = = y.hashCode ().
According to the inverse * *, if x.hashCode ()! = y.hashCode (), then x.equals (y) = = false must be true.
You don't need to guarantee that when x.equals (y) = = false, x.hashCode ()! = y.hashCode (). However, this will improve the performance of the hash table if you can make it as valid as possible.
The simplest legal implementation of hashCode () is simply return 0; although this implementation is correct, it can cause HashMap these data structures to run very slowly.
Reference: java.lang.Object.hashCode ().
Implement compareTo ()
Class Person implements Comparable {String firstName; String lastName; int birthdate; / / Compare by firstName, break ties by lastName, finally break ties by birthdate public int compareTo (Person other) {if (firstName.compareTo (other.firstName)! = 0) return firstName.compareTo (other.firstName); else if (lastName.compareTo (other.lastName)! = 0) return lastName.compareTo (other.lastName); else if (birthdate)
< other.birthdate) return -1; else if (birthdate >Other.birthdate) return 1; else return 0;}}
Always implement the generic version of Comparable instead of the original type Comparable. Because this can save the amount of code and reduce unnecessary trouble.
Only care about the positive and negative sign (negative / zero / positive) of the returned results, their size is not important.
The implementation of Comparator.compare () is similar to this.
Reference: java.lang.Comparable.
Implement clone ()
Class Values implements Cloneable {String abc; double foo; int [] bars; Date hired; public Values clone () {try {Values result = (Values) super.clone (); result.bars = result.bars.clone (); result.hired = result.hired.clone (); return result;} catch (CloneNotSupportedException e) {/ / Impossible throw new AssertionError (e);}
Use super.clone () to make the Object class responsible for creating new objects.
The basic type fields have been copied correctly. Again, we don't need to clone immutable types such as String and BigInteger.
Deep copy (deep copy) of all non-basic type fields (objects and arrays) manually.
For a class that implements Cloneable, the clone () method should never throw CloneNotSupportedException. Therefore, you need to catch the exception and ignore it, or wrap it with an unchecked exception.
It is possible and legal to implement the clone () method manually instead of using the Object.clone () method.
Reference: java.lang.Object.clone (), java.lang.Cloneable ().
Use StringBuilder or StringBuffer
/ join (["a", "b", "c"])-> "an and b and c" String join (List strs) {StringBuilder sb = new StringBuilder (); boolean first = true; for (String s: strs) {if (first) first = false; else sb.append ("and"); sb.append (s);} return sb.toString ();}
Don't use a 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 the toString () method to get the entire concatenated text.
StringBuilder is preferred because it is faster. All methods of StringBuffer are synchronized, and you usually don't need synchronized methods.
Refer to java.lang.StringBuilder, java.lang.StringBuffer.
Generate a random integer in a range
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 within a range of integers.
Don't try to use the uncertain usage of Math.abs (rand.nextInt ())% n, because its results are biased. In addition, its result value may be negative, such as when rand.nextInt () = = Integer.MIN_VALUE.
Reference: java.util.Random.nextInt (int).
Use Iterator.remove ()
Void filter (List list) {for (Iterator iter = list.iterator (); iter.hasNext ();) {String item = iter.next (); if (...) Iter.remove ();}}
The remove () method acts on the item recently returned by the next () method. The remove () method can only be used once per entry.
Reference: java.util.Iterator.remove ().
Reverse string
String reverse (String s) {return new StringBuilder (s). Reverse (). ToString ();}
This method should probably be added to the Java standard library.
Reference: java.lang.StringBuilder.reverse ().
Start a thread
The following three examples accomplish the same thing in different ways.
How to implement 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 causes the newly created thread to call run ().
Reference: java.lang.Thread, java.lang.Runnable.
Use try-finally
Example of Icano stream:
Void writeStuff () throws IOException {OutputStream out = new FileOutputStream (...); try {out.write (...);} finally {out.close ();}}
Examples of locks:
Void doWithLock (Lock lock) {lock.acquire (); try {...} finally {lock.release ();}}
If the statement before try fails and an exception is thrown, the finally statement block will not be executed. But in any case, there is no need to worry about the release of resources in this case.
If the statement in the try statement block throws an exception, the program will jump into the finally statement block to execute as many statements as possible, and then jump out of this method (unless the method has another outer finally statement block).
Read byte data from the 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, inclusive) or returns-1 when the end of the stream is reached.
Reference: java.io.InputStream.read ().
Read block data from the input stream
InputStream in = (...); try {byte [] buf = new byte; 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.
Reference: java.io.InputStream.read (byte []), java.io.InputStream.read (byte [], int, int).
Read text from a file
BufferedReader in = new BufferedReader (new InputStreamReader (new FileInputStream (...), "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 treats bytes and characters as two different concepts (which is different from C).
You can use any type of InputStream instead of FileInputStream, such as socket.
When the end of the stream is reached, BufferedReader.readLine () returns null.
To read one character at a time, use the Reader.read () method.
You can use other character encodings instead of UTF-8, but don't do this.
Reference: java.io.BufferedReader, java.io.InputStreamReader.
Write text to a file
PrintWriter out = new PrintWriter (new OutputStreamWriter (new FileOutputStream (...), "UTF-8"); try {out.print ("Hello"); out.print (42); out.println ("world!");} finally {out.close ();}
The creation of Printwriter objects is tedious. This is because Java treats bytes and characters as two different concepts (which is different from C).
Just like System.out, you can use print () and println () to print multiple types of values.
You can use other character encodings instead of UTF-8, but don't do this.
Reference: java.io.PrintWriter, java.io.OutputStreamWriter.
Preventive testing (Defensive checking) value
Int factorial (int n) {if (n)
< 0) throw new IllegalArgumentException("Undefined"); else if (n >= 13) throw new ArithmeticException ("Result overflow"); else if (n = 0) return 1; else return n * factorial (n-1);}
Do not think that the values entered are positive numbers, numbers that are small enough, and so on. These conditions should be explicitly detected.
A well-designed function should execute correctly for all possible input values. Make sure that all situations are taken into account and do not produce incorrect output (such as overflow).
Preventive detection object
Int findIndex (List list, String target) {if (list = = null | | target = = null) throw new NullPointerException ();...}
Do not assume that object parameters will not be empty (null). This condition should be explicitly detected.
Preventive detection array index
Void frob (byte [] b, int index) {if (b = = null) throw new NullPointerException (); if (index)
< 0 || index >= b.length) throw new IndexOutOfBoundsException ();...}
Do not assume that the array index given will not be out of bounds. It should be detected explicitly.
Preventive detection array interval
Void frob (byte [] b, int off, int len) {if (b = = null) throw new NullPointerException (); if (off)
< 0 || off >B.length | | len
< 0 || b.length - off < len) throw new IndexOutOfBoundsException(); ... } 不要认为所给的数组区间(比如,从off开始,读取len个元素)是不会越界。要显式地检测它。 填充数组元素 使用循环: // Fill each element of array 'a' with 123 byte[] a = (...); for (int i = 0; i < a.length; i++) a[i] = 123; (优先)使用标准库的方法: Arrays.fill(a, (byte)123); 参考:java.util.Arrays.fill(T[], T)。 参考:java.util.Arrays.fill(T[], int, int, T)。 复制一个范围内的数组元素 使用循环: // Copy 8 elements from array 'a' starting at offset 3 // to array 'b' starting at offset 6, // assuming 'a' and 'b' are distinct arrays byte[] a = (...); byte[] b = (...); for (int i = 0; i < 8; i++) b[6 + i] = a[3 + i]; (优先)使用标准库的方法: System.arraycopy(a, 3, b, 6, 8); 参考:java.lang.System.arraycopy(Object, int, Object, int, int)。 调整数组大小 使用循环(扩大规模): // Make array 'a' larger to newLen byte[] a = (...); byte[] b = new byte[newLen]; for (int i = 0; i < a.length; i++) // Goes up to length of A b[i] = a[i]; a = b; 使用循环(减小规模): // Make array 'a' smaller to newLen byte[] a = (...); byte[] b = new byte[newLen]; for (int i = 0; i < b.length; i++) // Goes up to length of B b[i] = a[i]; a = b; (优先)使用标准库的方法: a = Arrays.copyOf(a, newLen); 参考:java.util.Arrays.copyOf(T[], int)。 参考:java.util.Arrays.copyOfRange(T[], int, int)。 把4个字节包装(packing)成一个int int packBigEndian(byte[] b) { return (b[0] & 0xFF) >8), (byte) (x > 0)};} byte [] unpackLittleEndian (int x) {return new byte [] {(byte) (x > > 0), (byte) (x > 8), (byte) (x > 16), (byte) (x > 24)};}
Always packing bits with the unsigned right shift operator (> >). Do not use the arithmetic right shift operator (> >).
This is the end of the content of "how to use Java". Thank you for your reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.