Summary of common defects in Java programming (i)

Source: Internet
Author: User

[Case 1]

1  Public Boolean Equalnode (Judgenode A, Judgenode b) {2     return a.getid () = = B.getid (); 3 }

Reviews

The Equals () method should be defined in the Judgenode class (estimated to have just come from a process-oriented language ...).

"Case 2"

1  Public string[] getmsg () {2     New Arraylist<string> (2); 3       4     New string[msglist.size ()]; 5     Msglist.toarray (result); 6     return result; 7 }

Reviews

can be simplified to return new String[]{linkstatus.get (AC), getlinkmsg ()};

"Case 3"

1 Private BooleanBinteger (object[][] values,inti) { //development Environment Real Code 2     Booleanb =false;3     Try {4b = Values[0][i]instanceofInteger;5}Catch(Exception e) {6Logger.error ("Values[0][i] instanceof Integer Error:" +e);7b =false;8     }9     returnb;Ten}

Reviews

1. instanceof is an operator that does not throw exceptions such as null pointers, and, from the context, Values[0][i] does not appear to be out-of-bounds or other exceptions.

Therefore, you do not need to catch an exception when judging the type by instanceof. Further, the Binteger () method is meaningless and can be judged directly at the call point using instanceof.

2. When using the SLF4J log component, Logger.error (and Log.warn) accept the Throwable parameter to print the exception name and detailed stack information (possibly internally called E.printstacktrace ()).

But when you write a print statement, you need to be aware of the format. For example:

1 logger.error ("Best print:", e); 2 //a . 3 //b . or + e.tostring () 4 //c . Or: {} ", E.getmessage ())

A sentence can still print the exception name and stack information, but more output a pair of curly braces "{}"; b. Only the exception name is printed, and the C clause prints the exception message string. Take the null pointer exception (runtime exception) as an example, the B sentence prints "java.lang.NullPointerException", and the C sentence prints "null" (too primitive).

"Case 4"

1  PublicDbbatch (intCountthrowsSQLException {2Con =connnectionmanager.getconnection (dbconsts.db_source_name);3PreparedStatement =con.preparestatement (dbconsts.sql);4result =preparedstatement.executequery ();5      This. Count =count;6 }7  Public voidClose () {//Close Result\statement\connection8}

Reviews

You should avoid requesting resources in the constructor. If an exception occurs in the constructor dbbatch (int count) preparedstatement.executequery (), the above PreparedStatement, con, cannot be closed. At this point, external access to the Dbbatch object reference is not available, and the Dbbatch.close () method cannot be called, resulting in resource leaks.

"Case 5"

1 Private StaticString listtostring (list<string>columnlist) {2StringBuilder colname =NewStringBuilder (1000);//13      for(String s:columnlist) {4Colname.append (S + ",");5     }6Colname.deletecharat (Colname.length ()-1);//27     returncolname.tostring ();8}

Reviews

1. New StringBuilder (1000) initialization of the specified length is too large, resulting in wasted space.

Related information see "Talking about the expansion mechanism of HashMap, ArrayList and StringBuilder in Java".
2. When Columnlist is an empty collection, such as list<string> columnlist = Collections.emptylist (), an subscript out-of-bounds exception is thrown ( stringindexoutofboundsexception).
3. Use String.Join (",", columnlist) instead. If the output format of "[A, B, C, d]" is expected, the columnlist.tostring () can be used directly.

"Case 6"

1 Private Static BooleanCheckName1 (String name) {//cycles 10 million times, time consuming 350ms2list<string> NameList =NewArraylist<string>();3Namelist.add ("Lilei"); Namelist.add ("Hameimei"); Namelist.add ("Hedan");4Namelist.add ("Jame"); Namelist.add ("Lucy"); Namelist.add ("Beth");5     if(Namelist.contains (name)) {6         return true;7     }8     return false;9 }Ten  One Private Static BooleanCheckName2 (String name) {//cycles 10 million times, time consuming 1729ms ASet<string> NameSet =NewHashset<string>() { -{Add ("Lilei"); Add ("Hameimei"); Add ("Hedan")); -Add ("Jame"); Add ("Lucy"); Add ("Beth"); the         }}; -     returnnameset.contains (name); - } -  + Private Static FinalList<string> name_list =NewArraylist<string>() { -{Add ("Lilei"); Add ("Hameimei"); Add ("Hedan")); +Add ("Jame"); Add ("Lucy"); Add ("Beth"); A     }}; at Private Static BooleanCheckName3 (String name) {//cycles 10 million times, time consuming 110ms -     returnName_list.contains (NAME); - } -  - Private Static FinalSet<string> Name_set =NewHashset<string>() { -{Add ("Lilei"); Add ("Hameimei"); Add ("Hedan")); inAdd ("Jame"); Add ("Lucy"); Add ("Beth"); -     }};  to Private Static BooleanCheckName4 (String name) {//cycles 10 million times, time consuming 52ms +     returnName_set.contains (NAME); - } the  * Private Static BooleanCheckName5 (String name) {//cycles 10 million times, time consuming 46ms $     return"Lilei". Equals (name) | | "Hameimei". Equals (name) | | "Hedan". Equals (name) | |Panax Notoginseng"Jame". Equals (name) | | "Lucy". Equals (name) | | "Beth". Equals (name); -}

Reviews

1. Do not use "if (expression) return true; else return false; " Should be changed to "return expression;".

2. The list's contains () method internally calls the indexof () traversal to find the entire array, which is less efficient. If it involves large-scale data operation, we should choose map and other containers.

3. This case uses the timing method in the various implementations and efficiency comparisons of Java string connections to count the execution efficiency of checkname1~5 (). Results at a Glance ~

"Case 7"

1 map<string, string> apmap = constructapmap (); 2      for (String apId:apMap.keySet ()) {3     String Aptype = apmap.get (apId); 4     ... ...

Reviews

It is recommended to use Apmap.entryset to traverse the map instead of Keyset+get (actually traversing two times). Although the map get method is "fast", it can't be wasted!

See "KeySet and EntrySet traverse hashmap performance Differences" for related information.

EntrySet Simplified Syntax (Java 8 functional programming):

1 New Hashmap<>(); 2 Map.foreach (key, value), {3    ... 4 });

"Case 8"

1 Private Double [] Devanningarray (List<double> origin) {2     doublenewdouble [Origin.size ()]; 3      for (int i = 0; i < origin.size (); + +i) {4         target[i] = origin.get (i); 5         ... ...

Reviews

ArrayList random access, Time complexity O (1), LinkedList random access, time complexity O (n).

Recommendation: 1) Priority For-each, i.e. for (e:list) {};2), is recommended to be constrained from the interface contract, such as fun (ArrayList array) {}, if it has to be randomly accessed.

An overview of the features attached to the Java container class:

ArrayList package array, suitable for "read more write Less" scene, LinkedList doubly linked list, suitable for "write many" scenes, random access efficiency is low; Vector, Stack chicken hashmap, hashtable associative container, Hashtable synchronous TreeMap Red and black tree, ordered: Sort by logical size Linkedhashmap ordered: Sort by insertion Order hashset, TreeSet, Linkedhashset package corresponding to the Mapconcurrenthashmapconcurrentlinkedqueue, Concurrentlinkeddueue lock-free queue, with caution with Arrayblockingqueue, Linkedblockingqueue blocking queue copyonwritearraylist, Copyonwritearrayset tools, encapsulation class: Arrays.aslist, Collections.unmodifiablelist\set\map\collectioncollections.synchronizedlist\set\map\collection

Summary of common defects in Java programming (i)

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.