Java several common base errors

Source: Internet
Author: User

1.String equal

A little bit of experienced programmers will compare with equals instead of = =, but is it really safe to use equals, see the code below

User.getname (). Equals ("Xiaoming");

Experienced old drivers will soon be able to see the problem, if User.getname () is null, it throws a null pointer exception, so the following wording is more secure

"Xiaoming". Equals (User.getname ());

Of course, this kind of writing is not omnipotent, if the opposite sides are unknown variables, as follows

User.getname (). Equals (User1.getname ()); // User.getname () and User1.getname () are both likely to be null

Therefore, a more secure method can be used in the JDK objects class of the Equals method, both left and right can avoid null pointer exceptions

Objects.equals (User.getname (), User1.getname ());

It is important to note that the objects class is supported in jdk1.7, and if it is jdk1.6, the objects class in guava can be used instead

2.Integer comparison
Integer A = 127= 127=n = += = b); // The result is: true System.out.println (c = = d); // The result is: false

Surprisingly, the result is not expected to be all true, but one for true and one for false
As for the reasons, we need to explore the source code.

First look through the source code, when through = to the integer assignment, actually called the Integer.valueof () method

 Public Static Integer valueOf (int  i) {    assert integercache.high >= 127;     if (I >= integercache.low && i <= integercache.high)         return Integercache.cache[i + (-integercache.low)];     return New Integer (i);}

You can see that when I >= integercache.low && i <= Integercache.high, it is taken from a cache class, and other cases are new. Integercache.low default to -128,high is 127 (adjustable).

This a=b is good to explain, because = = compares the memory address, A, B is the same object taken from this cache class, so the return result is true. B,c are new objects and memory addresses are naturally different, so return false

Now that you see the cache class, it's worth seeing the truth.

Private Static classIntegercache {Static Final intLow =-128; Static Final intHigh ; Static FinalInteger cache[]; Static {        //High value is configured by property        intH = 127; String Integercachehighpropvalue=Sun.misc.VM.getSavedProperty ("Java.lang.Integer.IntegerCache.high"); if(Integercachehighpropvalue! =NULL) {            inti =parseint (Integercachehighpropvalue); I= Math.max (i, 127); //Maximum array size is Integer.max_valueh = math.min (i, Integer.max_value-(-low)-1); } High=h; Cache=Newinteger[(high-low) + 1]; intj =Low ;  for(intk = 0; K < Cache.length; k++) Cache[k]=NewInteger (j + +); }    PrivateIntegercache () {}}

Integercache is a static inner class in the integer class, and the high value can be set by the JVM's startup parameters

3.arrays.aslist (Array)
String [] array= {"A", "B", "C"}; // The returned list instance is: Java.util.Arrays.ArrayList list<string> list = arrays.aslist (array); List.remove (0);

Arrays.aslist is a very common way to create a list, but the list instance returned by the method is not the usual list instance, but a static inner class of Arrays that inherits from the Abstractlist class and provides a complete implementation of the list, such as the Remove method Now, of course, if it's just for traversal, it's perfectly fine.

There are a number of similar cases that you should pay attention to when using, for example:

    1. The Sublist method of ArrayList, which returns an inner class in ArrayListjava.util.ArrayList.SubList
    2. The values method of HashMap, which returns an inner class in HashMap:java.util.HashMap.Values
4.list.toarray
New Arraylist<string>(); string[] Array= (string[]) List.toarray ();

The above notation seems to be fine at first glance, but List.toarray () returns an object array with a strong transfer throw exception. You can actually specify the type of the returned array, as follows

String[] Array=list.toarray (new string[list.size ()));
5.foreach Remove
list<string> list =new arraylist<string>(), List.add ("Java"), List.add ("C" ); List.add ("JS");  for (String str:list) {  list.remove (0);}

The deletion of elements in the time-elapsed is also more commonly used, but the deletion of elements in foreach can throw an exception, this kind of bad control of the writing is not good, you can use iterators to replace

 for (iterator<string> Iterator = list.iterator (); Iterator.hasnext ();) {  = iterator.next ();  Iterator.remove ();}
6. String GetBytes
String str= "Wade"; byte [] bytes = Str.getbytes ();

The string's GetBytes () method uses the default encoding of the current project, and if you do not specify the encoding, it is easy to be trapped in a different operating environment, so you can still specify the corresponding encoding according to your own needs.

String str= "Wade"; byte [] bytes = Str.getbytes ("Utf-8");






Zhaoguhong (Zhao Gu Hong)

Source: http://www.cnblogs.com/zhaoguhong/

This article is copyrighted by the author and the blog Park, reproduced please indicate the source

Java several common base errors

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.