Several common basic errors in java and common basic errors in java

Source: Internet
Author: User

Several common basic errors in java and common basic errors in java
1. Equal String

Programmers with a little experience will use equals instead of =. But is it really safe to use equals? Check the following code.

user.getName().equals("xiaoming");

Experienced drivers will soon be able to see the problem. If user. getName () is null, a null pointer exception will be thrown, so the following statement is more secure

"xiaoming".equals(user.getName());

Of course, this writing method is not omnipotent. If both sides of the comparison are unknown variables

User. getName (). equals (user1.getName (); // both user. getName () and user1.getName () may be null.

Therefore, you can use the equals method in the jdk Objects class in a more secure way. both the left and right sides can avoid NULL pointer exceptions.

Objects.equals(user.getName(), user1.getName());

It should be noted that the Objects class is supported in jdk1.7. If it is jdk1.6, it can be replaced by the Objects class in guava.

2. Integer comparison
Integer a = 127; Integer B = 127; Integer c = 128; Integer d = 128; System. out. println (a = B); // The result is trueSystem. out. println (c = d); // The result is: false.

Surprisingly, not all the results are expected to be true, but one is true and the other is false.
As for the reason, we also need to explore from the source code.

First, let's take a look at the source code. When an Integer is assigned a value through =, the Integer. valueOf () method is actually called.

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);}

We can see that when I> = IntegerCache. low & I <= IntegerCache. high, it is taken from a cache class. In other cases, it will create an object. IntegerCache. low is-128 by default, and high is 127 by default (adjustable ).

In this way, a = B is well explained, because = compares the memory address, a and B are all the same objects from this cache class, so the return result is true. B and c are all new objects, and the memory address is naturally different. Therefore, false is returned.

Now that we see this cache class, we need to see its true nature.

private static class IntegerCache {    static final int low = -128;    static final int high;    static final Integer cache[];    static {        // high value may be configured by property        int h = 127;        String integerCacheHighPropValue =            sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");        if (integerCacheHighPropValue != null) {            int i = parseInt(integerCacheHighPropValue);            i = Math.max(i, 127);            // Maximum array size is Integer.MAX_VALUE            h = Math.min(i, Integer.MAX_VALUE - (-low) -1);        }        high = h;        cache = new Integer[(high - low) + 1];        int j = low;        for(int k = 0; k < cache.length; k++)            cache[k] = new Integer(j++);    }    private IntegerCache() {}}

IntegerCache is a static internal class in the Integer class. The high value can be set through the JVM startup parameter.

3. Arrays. asList (array)
String [] array = {"a", "B", "c"}; // The returned List instance is java. util. arrays. arrayListList <String> list = Arrays. asList (array); list. remove (0 );

Arrays. asList is a common method for creating a List. However, the List instance returned by this method is not a List instance that is commonly used, but a static internal class of Arrays, which inherits from the javasactlist class, and to provide the complete implementation of the List, for example, the remove method is not implemented. Of course, if it is just used for traversal, it is completely OK.

There are many other similar cases. Pay attention to them when using them, for example:

4. list. toArray
List<String> list = new ArrayList<String>();String[] array=(String[]) list.toArray();

At first glance, there seems to be no problem, but list. toArray () returns an array of objects, throwing an exception during a strong transfer. You can 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);}

It is also a common operation to delete elements in a time-on-time manner. However, an exception may be thrown When deleting elements in foreach. This method is difficult to control and can be replaced by an iterator.

for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {  String str = iterator.next();  iterator.remove();}
6. String getBytes
String str = "Wade"; byte [] bytes = str. getBytes ();

The getBytes () method of String uses the default encoding of the current project. If no encoding is specified, it is easy to be pitted in different runtime environments, therefore, it is more reliable to specify the corresponding encoding according to your own needs.

String str = "Wade"; byte [] bytes = str. getBytes ("UTF-8 ");

 






Author: zhaoguhong (Zhao Guhong)

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

The copyright of this article is shared by the author and the blog site. For more information, see the source.

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.