reading notes

1. Try to use basic types, because the case of null == int, performance issues, problem 3 Comparative problem

Comparator<Integer> order = (i, j) -> (i < j) ? -1 : ((i == j) ? 0 : 1);
int compare = order.compare(new Integer(2), new Integer(2) );
System.out.println(compare);

Here's expected output should be zero, but actually is one. Analysis, i <j here automatically unpacking into NT, then i == j, == where object reference is determined, it is false, 0 is drawn up.

This changed following it.

        Comparator<Integer> order = (i, j) -> {
            int a = i, b = j;
            return i < j ? -1 : (i == j ? 0 : 1);
        };

Also to be noted that the following error code, it will be a null pointer exceptions, but the compiler. Will function as Integer values ​​are null, null == int there is such a case, it should be replaced by the definition int i.

 static Integer i;
    public static void main(String[] args) {
        if (i == 2) {
            System.out.println("ok");
        }
    }

 So, what type of packaging should be used when it? They have a few legitimate uses. The first is as a collection of elements, key and value. Can not be set in the basic type, package types must be used. This is a special case in the general case. In parameterized types and methods must be used as a type of packaging type parameter is not allowed because the Java primitive types. For example, a variable can not be declared as ThreadLocal <int> type must be used ThreadLocal <Integer>. After carrying out the reflection method is called, must be used type of packaging.

In short, as long as the selection, priority should be given to use basic types, rather than the type of packaging. Basic types easier and faster. If you must use the type of packaging, please be careful! Autoboxing reduce lengthy use of packaging types, but there is no risk reduction. When your program uses the == operator to compare two types of packaging, it will perform identity comparison, this is almost certainly not what you want. When your program is executed with mixed type packaging type and basic type of calculation, it will be unpacking When unpacking your program execution, will throw NullPointerException. Later, when your program will be basic types of packing, it can lead to costly and unnecessary object creation.

 

2. Try to avoid using strings, very conventional ideas, not elaborate too much

3. Minimize the use of reflection, reflection can indeed be achieved access to any class, but cumbersome and not very safe (the compiler does not check), performance badly. The following write an example

 

 

 

 

Guess you like

Origin www.cnblogs.com/CherryTab/p/11908879.html