Java Advanced Effective Java Notes (1)

1. Primitive types take precedence over boxed primitive types

The type system of java can be divided into basic types and reference types, such as int, double; reference types such as string list; each basic type has its corresponding reference type, which is called a boxed basic type.

Understand that everything in java is an object; primitive types only have values, and boxed types are a class.

What is auto-boxing and auto-unboxing?

The act of extracting the value of a primitive type used for a boxed type pair is called auto-unboxing: when an operation mixes primitives and boxed primitives, the boxed primitive is automatically unboxed.

 

The difference between primitive types and boxed primitive types:

1. Primitive types have only values, while wrapper types have an identity different from their values. This identity refers to whether two references point to the same object, and if they point to the same object, it means they are identical. (Similar to this is equivalence.)

2. Basic types only have fully functional values, while wrapper types have a non-functional value in addition to all the functions of their corresponding basic types: null.

3. Basic types usually save time and space than packaging types.

 

In the following three places, the use of wrapper types will be more reasonable :
      1. As elements, keys and values ​​in collections.
      2. In parameterized types. For example: You can't write like this - ArryList<int>, you can only write ArrayList<Integer>.
      3. When calling the reflection method.

 

There are a few things to keep in mind when you must use boxed primitives:

   * 1: Compare whether the values ​​of the objects are equal, you cannot use ==, you must use equals
   *2: When the program performs mixed type calculations involving boxing and unboxing primitive types, it will perform unboxing, and when the program performs unboxing, a null pointer exception may be thrown.
   *3: When programs box primitive values, it causes high overhead and unnecessary object creation.

 

Summary: When you can choose, you should try to use the basic type, which is simpler and faster.

 

 

 

two,

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325790704&siteId=291194637