📜  Java中的自动装箱和拆箱

📅  最后修改于: 2022-05-13 01:54:43.331000             🧑  作者: Mango

Java中的自动装箱和拆箱

在Java中,原始数据类型的处理方式不同,因此引入了包装类,其中两个组件发挥作用,即自动装箱和拆箱。自动装箱是指将原始值转换为相应包装类的对象,称为自动装箱。例如,将 int 转换为 Integer 类。 Java编译器在原始值是以下情况时应用自动装箱:

  • 作为参数传递给需要相应包装类的对象的方法。
  • 分配给相应包装类的变量。

另一方面,拆箱是指将包装类型的对象转换为其相应的原始值。例如将 Integer 转换为 int。 Java编译器适用于拆箱时包装类的对象是:

  • 作为参数传递给需要相应原始类型的值的方法。
  • 分配给相应原始类型的变量。
Primitive TypeWrapper Class
booleanBoolean
byteByte
charCharacter
float Float
int Integer
longLong
short Short
doubleDouble

下表列出了Java编译器用于自动装箱和拆箱的基本类型及其对应的包装类。现在让我们讨论自动装箱和拆箱的一些优点,以了解我们使用它的原因。

  • 自动装箱和拆箱使开发人员可以编写更简洁的代码,使其更易于阅读。
  • 该技术让我们可以互换使用原始类型和 Wrapper 类对象,并且我们不需要显式地执行任何类型转换。

示例 1:

Java
// Java program to illustrate the Concept
// of Autoboxing and Unboxing
 
// Importing required classes
import java.io.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an Integer Object
        // with custom value say it be 10
        Integer i = new Integer(10);
 
        // Unboxing the Object
        int i1 = i;
 
        // Print statements
        System.out.println("Value of i:" + i);
        System.out.println("Value of i1: " + i1);
 
        // Autoboxing of character
        Character gfg = 'a';
 
        // Auto-unboxing of Character
        char ch = gfg;
 
        // Print statements
        System.out.println("Value of ch: " + ch);
        System.out.println(" Value of gfg: " + gfg);
    }
}


Java
// Java Program to Illustrate Autoboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty Arraylist of integer type
        ArrayList al = new ArrayList();
 
        // Adding the int primitives type values
        // using add() method
        // Autoboxing
        al.add(1);
        al.add(2);
        al.add(24);
 
        // Printing the ArrayList elements
        System.out.println("ArrayList: " + al);
    }
}


Java
// Java Program to Illustrate Autoboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of integer type
        List list = new ArrayList();
 
        // Adding the int primitives type values by
        //  converting them into Integer wrapper object
        for (int i = 0; i < 10; i++)
 
            System.out.println(
                list.add(Integer.valueOf(i)));
    }
}


Java
// Java Program to Illustrate Find Sum of Odd Numbers
// using Autoboxing and Unboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // To sum odd numbers
    public static int sumOfOddNumber(List list)
    {
 
        // Initially setting sum to zero
        int sum = 0;
 
        for (Integer i : list) {
 
            // Unboxing of i automatically
            if (i % 2 != 0)
                sum += i;
 
            // Unboxing of i is done automatically
            // using intvalue implicitly
            if (i.intValue() % 2 != 0)
                sum += i.intValue();
        }
 
        // Returning the odd sum
        return sum;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of integer type
        List list = new ArrayList();
 
        // Adding the int primitives type values to List
        for (int i = 0; i < 10; i++)
            list.add(i);
 
        // Getting sum of all odd numbers in List
        int sumOdd = sumOfOddNumber(list);
 
        // Printing sum of odd numbers
        System.out.println("Sum of odd numbers = "
                           + sumOdd);
    }
}


输出:

让我们了解编译器如何在Java中使用泛型的集合示例中进行自动装箱和拆箱。

示例 2:

Java

// Java Program to Illustrate Autoboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty Arraylist of integer type
        ArrayList al = new ArrayList();
 
        // Adding the int primitives type values
        // using add() method
        // Autoboxing
        al.add(1);
        al.add(2);
        al.add(24);
 
        // Printing the ArrayList elements
        System.out.println("ArrayList: " + al);
    }
}
输出
ArrayList: [1, 2, 24]

输出说明:

在上面的示例中,我们创建了一个 Integer 类型的元素列表。我们正在添加 int 原始类型值而不是 Integer Object,并且代码已成功编译。它不会生成编译时错误,因为Java编译器会从原始 int i 创建一个整数包装对象并将其添加到列表中。

示例 3:

Java

// Java Program to Illustrate Autoboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of integer type
        List list = new ArrayList();
 
        // Adding the int primitives type values by
        //  converting them into Integer wrapper object
        for (int i = 0; i < 10; i++)
 
            System.out.println(
                list.add(Integer.valueOf(i)));
    }
}
输出
true
true
true
true
true
true
true
true
true
true

自动和拆箱的另一个示例是在列表中查找奇数的总和。程序中的一个重点是运算符余数 (%) 和一元加号 (+=)运算符不适用于 Integer 对象。但是,代码仍然可以成功编译,因为通过在运行时调用 intValue() 方法将 Integer Object 拆箱为原始 int 值。

示例 4:

Java

// Java Program to Illustrate Find Sum of Odd Numbers
// using Autoboxing and Unboxing
 
// Importing required classes
import java.io.*;
import java.util.*;
 
// Main class
class GFG {
 
    // Method 1
    // To sum odd numbers
    public static int sumOfOddNumber(List list)
    {
 
        // Initially setting sum to zero
        int sum = 0;
 
        for (Integer i : list) {
 
            // Unboxing of i automatically
            if (i % 2 != 0)
                sum += i;
 
            // Unboxing of i is done automatically
            // using intvalue implicitly
            if (i.intValue() % 2 != 0)
                sum += i.intValue();
        }
 
        // Returning the odd sum
        return sum;
    }
 
    // Method 2
    // Main driver method
    public static void main(String[] args)
    {
 
        // Creating an empty ArrayList of integer type
        List list = new ArrayList();
 
        // Adding the int primitives type values to List
        for (int i = 0; i < 10; i++)
            list.add(i);
 
        // Getting sum of all odd numbers in List
        int sumOdd = sumOfOddNumber(list);
 
        // Printing sum of odd numbers
        System.out.println("Sum of odd numbers = "
                           + sumOdd);
    }
}
输出
Sum of odd numbers = 50