java 中的 wrapper 和 Auto Boxing/Unboxing 有什么区别?

What is difference between wrapper and Auto Boxing/Unboxing in java?

A​​ Wrapper Class 用于将图元转换为对象,将对象转换为图元。类似地,通过使用 AutoboxingUnboxing 我们可以做同样的事情,那么这两者有什么区别: 1-概念明智 2-代码明智???

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes. For example, converting an int to an Integer, a double to a Double, and so on. If the conversion goes the other way, this is called unboxing.

这是最简单的自动装箱示例:

 Character ch = 'a';

The wrapper classes provide a mechanism to "wrap" primitive values in an object so that the primitives can be included in activities only for objects, like being added to Collections. There is a wrapper class for every primitive in Java. The wrapper class for int is Integer and the class for float is Float and so on. Wrapper classes also provide many utility functions for primitives like Integer.parseInt().

创建包装器对象的三种最常见的方法是:

1.使用构造函数作为

 Integer i1 = new Integer(42);

除 Character 之外的所有包装器 classes 都提供了两个构造函数:一个采用原始类型,另一个采用原始类型的 String 表示形式:new Integer(42) 或 new Integer("42 ”)。 Character class 只提供一个构造函数,它以一个 char 作为参数:new Character('c').

2。使用 valueOf() 作为

 Float f2 = Float.valueOf("3.14f");

3。直接将基元分配给包装器引用,在这种情况下 java 将自动为您创建一个对象,这称为自动装箱 as

 Long weight = 1200L;

包装器 class 有很多实用函数,主要用于转换,例如:

  double d4 = Double.parseDouble("3.14");

  Double d5 = Double.valueOf("3.14");

自动装箱和自动拆箱只是编译器默默地帮助您创建和使用原始包装器对象。

例如,int 原始类型具有名为 Integer 的包装器 class。您按如下方式包装和解包:

int myInt = 7;

// Wrap the primitive value
Integer myWrappedInt = Integer.valueOf(myInt);

// Unwrap the value
int myOtherInt = myWrappedInt.intValue();

使用自动装箱和自动拆箱,您不必做所有这些样板式的事情:

int myInt = 7;

// Wrap the primitive value
Integer myWrappedInt = myInt; // Compiler auto-boxes

// Unwrap the value
int myOtherInt = myWrappedInt; // Compiler auto-unboxes

它只是一个语法糖,由编译器处理。生成的字节码是一样的

Wrapper 类 in java 提供了一种将基元转换为对象以及将对象转换为基元的机制。而自动装箱和拆箱允许您自动进行转换。自动装箱和自动拆箱在 java 中是合法的,因为 Java 5.

public class Main {

    public static void main(String[] args) {
        int x=100;
        Integer iob;
        iob=x;//illegal upto JDK1.4
        iob= Integer.valueOf(x); //legal=> Boxing,Wrapping
        iob=x; //Legal since JDK1.5=> Auto Boxing

    }
}

这里x是原始变量,iob是引用变量。因此只能将地址分配到此 iob 引用中。 iob=Integer.valueOf(x) 将原始整数转换为整数对象。这种转换可以隐含为包装。 iob=x 会做同样的事情。它还可以节省大量编码。

public class Main {

    public static void main(String[] args) {
        Integer iob= new Integer(100);
        int x;

        x=iob;//illegal upto JDK1.4
        x=iob.intValue(); //unboxing,unwrapping

        x=iob; //legal since JDK1.5=> auto unboxing 

    }
}

此处iob.intValue()将获取整数对象的值并将该值赋给x。 x=iob 做同样的事情,除了你不需要写转换代码。