java中自动装箱和拆箱_Java中的自动装箱和拆箱

java中自动装箱和拆箱

In Java 1.5, Java added concept of autoboxing and unboxing that deal with conversion of primitive type to object and vice versa.

在Java 1.5中,Java添加了自动装箱和拆箱的概念,用于处理从原始类型到对象的转换,反之亦然。

The term autoboxing refers to the auto conversion of primitive type to its correspond object type. For example, conversion of int type to Integer object or char type to Character object. This conversion is done implicitly by the Java compiler during program execution.

术语自动装箱是指将原始类型自动转换为其对应的对象类型。 例如,将int类型转换为Integer对象或将char类型转换为Character对象。 Java编译器在程序执行期间隐式完成了此转换。

In the same context, when an object coverts to its correspond primitive type then it is called unboxing. For example, conversion of Integer type to int type or Byte to byte type etc. Java automatically performs this conversion during program execution.

在相同的上下文中,当一个对象隐蔽为其对应的原始类型时,则称为拆箱 。 例如,将Integer类型转换为int类型或将Byte转换为字节类型等。Java在程序执行期间自动执行此转换。

自动装箱示例 (Example of Autoboxing)

In this example, we are assigning an int type value to Integer object and notice compiler does not report any error because it performs autoboxing here.

在此示例中,我们为Integer对象分配了一个int类型值,并且注意编译器不会报告任何错误,因为它在此处执行自动装箱。

class Demo
{
	public static void main(String[] args)
	{
		Integer i = 100; // Auto-boxing of int i.e converting primitive data type int to a Wrapper class Integer
		System.out.println(i);

		Character ch = 'a'; 
		System.out.println(ch);
		
		Byte b = 12;
		System.out.println(b);
		
	}
}

100 a 12

100一12

说明: (Explanation:)

Whenever we use object of Wrapper class in an expression, autoboxing is done by JVM.

每当我们在表达式中使用Wrapper类的对象时,自动装箱便由JVM完成。

This will happen always, when we will use Wrapper class objects in expressions or conditions etc.

当我们在表达式或条件等中使用Wrapper类对象时,这总是会发生的。

示例:集合中的自动装箱 (Example: Autoboxing in Collection)

import java.util.ArrayList;

class Demo
{
	public static void main(String[] args)
	{
		ArrayList<Integer> arrayList = new ArrayList<Integer>();
		arrayList.add(100); // autoboxing int to Integer
		arrayList.add(200);
		arrayList.add(300);
		for(Integer i : arrayList) {
			System.out.println(i);
		}
	}
}

100 200 300

100200300

In the same manner, we can perform unboxing. Lets see an example.

以相同的方式,我们可以执行拆箱。 让我们来看一个例子。

示例:拆箱 (Example : Unboxing)

In this example, we using arraylist to store int type values. Since arraylist stores only object then it automatically converts int type to Integer and store the elements. If we fetch the elements of it returns object type and if we store it into primitive int type then it automatically converts Integer to int type. See the below example.

在此示例中,我们使用arraylist存储int类型值。 由于arraylist仅存储对象,因此它将自动将int类型转换为Integer并存储元素。 如果获取它的元素,则返回对象类型,如果将其存储为原始int类型,则它将自动将Integer转换为int类型。 请参见以下示例。

import java.util.ArrayList;

class Demo
{
	public static void main(String[] args)
	{
		ArrayList
   
   
    
     arrayList = new ArrayList
    
    
     
     ();
		arrayList.add(100); // autoboxing int to Integer
		arrayList.add(200);
		arrayList.add(300);
		for(Integer i : arrayList) {
			System.out.println(i);
		}
		// unboxing Integer to int type
		int first = arrayList.get(0);
		System.out.println("int value "+first);
	}
}
	
    
    
   
   

100 200 300 int value 100

100200300整数值100

自动装箱/拆箱的好处 (Benefits of Autoboxing / Unboxing)

  1. Autoboxing / Unboxing lets us use primitive types and Wrapper class objects interchangeably.

    自动装箱/拆箱使我们可以互换使用原始类型和Wrapper类对象。

  2. We don't have to perform Explicit typecasting.

    我们不必执行显式类型转换

  3. It helps prevent errors, but may lead to unexpected results sometimes. Hence must be used with care.

    它有助于防止错误,但有时可能会导致意外结果。 因此,必须谨慎使用。

  4. Auto-unboxing also allows you to mix different types of numeric objects in an expression. When the values are unboxed, the standard type conversions can be applied.

    自动拆箱还允许您在表达式中混合使用不同类型的数字对象。 将值取消装箱后,可以应用标准类型转换。

例: (Example:)

class Demo {
	public static void main(String args[]) {
		Integer i = 35;
		Double d = 33.3;
		d = d + i;
		System.out.println("Value of d is " + d);
	}
}

Value of d is 68.3

d的值是68.3

Note: When the statement d = d + i; was executed, i was auto-unboxed into int, d was auto-unboxed into double, addition was performed and then finally, auto-boxing of d was done into Double type Wrapper class.

注意:当语句d = d + i时; 执行后,我被自动拆箱为int,将d自动拆箱为double,执行了加法运算,最后将d的自动装箱完成为Double type Wrapper类。

类型包装纸 (Type Wrappers)

Java uses primitive data types such as int, double, float etc. to hold the basic data types for the sake of performance. Despite the performance benefits offered by the primitive data types, there are situations when you will need an object representation of the primitive data type. For example, many data structures in Java operate on objects. So you cannot use primitive data types with those data structures. To handle such type of situations, Java provides type Wrappers which provide classes that encapsulate a primitive type within an object.

为了性能起见,Java使用原始数据类型(例如int,double,float等)来保存基本数据类型。 尽管原始数据类型提供了性能上的好处,但是在某些情况下,您仍然需要原始数据类型的对象表示。 例如,Java中的许多数据结构都对对象进行操作。 因此,不能将原始数据类型与这些数据结构一起使用。 为了处理这种情况,Java提供了类型包装器 ,该包装器提供了将对象中的原始类型封装起来的类。

Java provides wrapper classes correspond to each primitive type to deal with objects that are tabled below.

Java提供了与每种基本类型相对应的包装器类,以处理下表中列出的对象。

PrimitiveWrapper class
intInteger
byteByte
shortShort
floatFloat
doubleDouble
charCharacter
longLong
booleanBoolean
原始 包装类
整型 整数
字节 字节
浮动 浮动
烧焦 字符
布尔值 布尔型

Above mentioned Classes comes under Numeric type wrapper. These classes encapsulate byte, short, int, long, float, double primitive type.

上面提到的类在数字类型包装器下。 这些类封装了byte,short,int,long,float,double基本类型。

示例:方法中的自动装箱和拆箱 (Example: Autoboxing and Unboxing in method)

We can see how autoboxing and unboxing take place in a method. Notice, during method call we passed int type primitive value but method accepts only Integer objects so here JVM does autoboxing implicitly. And notice, this method returns an int type primitive which is another conversion (unboxing) from Integer to int type.

我们可以看到自动装箱和拆箱的方法。 注意,在方法调用期间,我们传递了int类型的原始值,但是方法仅接受Integer对象,因此JVM在此隐式进行自动装箱。 请注意,此方法返回一个int类型原语,这是从Integer到int类型的另一种转换(拆箱)。

class Demo {
	// autoboxing in parameters
	static int add(Integer a, Integer b) {
		// unboxing in return
		return a+b;
	}
	
	public static void main(String args[]) {
		
		int sum = add(10,20);
		
		System.out.println("sum = "+sum);
		
		}
}

sum = 30

总和= 30

翻译自: https://www.studytonight.com/java/autoboxing-unboxing-java.php

java中自动装箱和拆箱

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值