Original link: https://docs.oracle.com/javase/tutorial/java/data/autoboxing.html
First, autoboxing
Autoboxing is an automatic conversion feature from the original type to the corresponding wrapper type (wrapper classes) provided by the Java compiler. such as int to integer,double turn double. If the package type is converted to the original type, it is called unboxing.
One of the simplest examples of autoboxing:
Character ch = ' a ';
There are also some autoboxing that are implemented by generic programming (generics/updated), such as:
list<integer> li = new arraylist<> (), for (int i = 1; i <; i + = 2) li.add (i);
Because Li is a list of integer objects rather than a list of int, the compiler creates an integer object with each I and joins Li, so the actual process can be represented as follows:
list<integer> li = new arraylist<> (), for (int i = 1; i <; i + = 2) li.add (integer.valueof (i));
The process of converting int i into an Integer object is called Autoboxing.
The Java compiler uses autoboxing in the following cases:
1. When the method is passed, the actual parameter of an original type is passed to a formal parameter which needs the corresponding wrapper class object;
2. A value of the original type is assigned to its corresponding wrapper class.
Second, unboxing
Consider the following scenario:
public static int Sumeven (list<integer> li) { int sum = 0; for (Integer I:li) if (i% 2 = = 0) sum + = i; return sum;}
Since the integer object does not have a modulo% and + = operator, the compiler will convert the integer to int at run time, which is unboxing. So the actual process is as follows:
public static int Sumeven (list<integer> li) { int sum = 0; for (Integer I:li) if (I.intvalue ()% 2 = = 0) sum + = I.intvalue (); return sum;}
The Java compiler uses unboxing in the following cases:
1. When the method is passed, the actual parameters of a wrapper class object are passed to a formal parameter that requires the corresponding primitive type;
2. The value of a wrapper class object is assigned to its corresponding primitive type.
Import Java.util.arraylist;import Java.util.list;public class Unboxing {public static void Main (string[] args) {
integer i = new Integer ( -8); 1. Unboxing through method invocation int absval = Absolutevalue (i); SYSTEM.OUT.PRINTLN ("absolute value of" + i + "=" + Absval); list<double> ld = new arraylist<> (); Ld.add (3.1416); Πis autoboxed through method invocation. 2. Unboxing through assignment double pi = ld.get (0); System.out.println ("PI =" + pi); } public static int Absolutevalue (int i) { return (i < 0)?-i:i; }}
Summarize:
Autoboxing and unboxing make the developer's code more concise and readable, and the following table is the corresponding conversion commonly used in autoboxing and unboxing.
Primitive type |
Wrapper class |
Boolean |
Boolean |
Byte |
Byte |
Char |
Character |
Float |
Float |
Int |
Integer |
Long |
Long |
Short |
Short |
Double |
Double |
[Java] Autoboxing & Unboxing