Java:自动装箱和强制转换之间有什么区别?

发布于 2024-07-13 10:17:55 字数 222 浏览 11 评论 0原文

这个问题是关于“为什么自动装箱会使一些Java 中调用不明确?”

但通读答案,有很多关于选角的参考,我不确定我是否完全理解其中的区别。

有人可以提供一个简单的解释吗?

This question is about "Why does autoboxing make some calls ambiguous in Java?"

But reading through the answers, there are a number of references to casting and I'm not sure I completely understand the difference.

Can someone provide a simple explanation?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

喵星人汪星人 2024-07-20 10:17:56

装箱和拆箱是 Java 中的一种类型转换,您可以从基元转换为其包装类或反之,例如,布尔值转换为布尔值(装箱),或布尔值转换为布尔值(拆箱)。

Java 中的强制转换类型,例如:

  • 身份转换 (§5.1.1)
    字符串到字符串

  • 扩大基元转换(第 5.1.2 节)
    byte 到 int

  • 缩小原语转换 (§5.1.3)
    int 到 byte

  • 扩大引用转换 (§5.1.5)
    整数到数字

  • 缩小引用转换(§5.1.6)
    数字到整数

  • 拳击转换 (§5.1.7)
    int 到 Integer

  • 拆箱转换(第 5.1.8 节)。
    整数到 int

自动装箱或自动拆箱会发生(它没有作为强制转换表达式显式出现在源代码中),例如请参阅您提到的问题。

Boxing and unboxing is a type of cast in Java, where you cast from a primitive to its wrapper class or the inverse, e.g. boolean to Boolean (box), or Boolean to boolean (unbox).

Types of casts in Java, with example:

  • an identity conversion (§5.1.1)
    String to String

  • a widening primitive conversion (§5.1.2)
    byte to int

  • a narrowing primitive conversion (§5.1.3)
    int to byte

  • a widening reference conversion (§5.1.5)
    Integer to Number

  • a narrowing reference conversion (§5.1.6)
    Number to Integer

  • a boxing conversion (§5.1.7)
    int to Integer

  • an unboxing conversion (§5.1.8).
    Integer to int

Autoboxing or autounboxing happens when the compiler does the boxing/unboxing conversion for you (it doesn't explicitly appear in the source code as a cast expression), e.g. see the question you referred to.

十秒萌定你 2024-07-20 10:17:56

自动装箱和拆箱是否可以应用于以下情况?

Long one = 10;
long two = 15;
Long three = 20;

if(one == three) //will this be unboxed or do we need to put a explicit
                 //condition like if(one.intValue() == three.intValue()) 
   System.out.println("Equal");
else 
   System.out.println("Not Equal");  


if(one == two) //will this be unboxed or do we need to put a explicit
               //condition like if(one.intValue() == two) 
   System.out.println("Equal");
else 
   System.out.println("Not Equal");  

Does Autoboxing and Unboxing can be applied in the following case ?

Long one = 10;
long two = 15;
Long three = 20;

if(one == three) //will this be unboxed or do we need to put a explicit
                 //condition like if(one.intValue() == three.intValue()) 
   System.out.println("Equal");
else 
   System.out.println("Not Equal");  


if(one == two) //will this be unboxed or do we need to put a explicit
               //condition like if(one.intValue() == two) 
   System.out.println("Equal");
else 
   System.out.println("Not Equal");  
樱娆 2024-07-20 10:17:55

装箱是将原始类型转换为引用类型,拆箱则相反。 强制转换是指当您希望将一种类型视为另一种类型时,在基本类型和引用类型之间,这意味着隐式或显式装箱操作。 是否需要明确是语言特性。

Boxing is when you convert a primitive type to a reference type, un-boxing is the reverse. Casting is when you want one type to be treated as another type, between primitive types and reference types this means an implicit or explicit boxing operation. Whether it needs to be explicit is a language feature.

鹊巢 2024-07-20 10:17:55

强制转换和装箱/拆箱都与类型和表观(或真实)转换有关,但装箱/拆箱特定于基元类型与其相应的包装类型之间的关系,而强制转换是显式或隐式类型更改的术语。更一般的意义。

强制转换是一个通用术语,具有两个相关但不同的含义:

  1. 将一种类型的值视为另一种类型的值。 首次使用的两个示例是:

    1.1。 鉴于类 B 扩展了类 A,您可以要求 myBB 的实例视为只要出现对 A 实例的引用,就可以通过编写 ((A) myB) 来实现 A 的实例。 这实际上并不会生成 A 的新实例。

    1.2。 Java5 之前的集合将所有内容存储为 Object; 这通常要求您在从集合中检索对象后使用强制转换。 例如,如果您在 Map 中存储了 String 并需要获取其长度,则可以编写类似 ((String) myMap.get( someKey)).length() 其中需要进行强制转换才能调用 Stringlength 方法。 同样,这不会导致创建新的String

  2. 显式转换一种类型为另一种类型(即显式更改表示形式)。 第二种用法的一个示例是表达式 ((int) (float_var + 0.5F)),它通过添加 0.5(生成浮点值)来舍入浮点变量,然后显式将该值转换为整数。 生成的整数值((int) 转换之后)是通过内部计算从另一个值生成的。

当存在超类/子类或接口/实现者关系(即上面的 1)或两种类型都是原始数字类型(即 2)时,可以进行强制转换。 您可以查找“加宽”和“缩小”以获取更多详细信息。

装箱是指将原始类型包装在容器对象中,通常仅在必须拥有对象时才执行(例如在集合中存储值)。 原始类型和包装类型成对出现:

int      Integer
long     Long
boolean  Boolean
...      ...

拆箱仅仅意​​味着从其对象包装中检索原始值。

从 Java5 开始,当您编写使用原始值的表达式时,需要相应的包装类型(例如将整数放入集合中),编译器会自动插入实际包装该原始值的代码。 同样,它将为您提供解包代码。

而不是编写(在 Java5 之前)类似的内容。

Map myMap = new HashMap();
...
myMap.put(someKey,Integer.valueOf(3));
...
int nextValue = (myMap.get(someKey)).intValue() + 1;

因此,您可以编写:

Map<KeyType,Integer> myMap = new HashMap<KeyType,Integer>();
...
myMap.put(someKey,3);
...
int nextValue = myMap.get(someKey) + 1;

并且装箱/拆箱代码由编译器插入,

Both casting and boxing/unboxing have to do with types and apparent (or real) conversion, but boxing/unboxing is specific to the relationship between primitive types and their corresponding wrapper types, while casting is the term for explicit or implicit change of type in the more general sense.

Casting is a general term with two related-but-different meanings:

  1. Treating a value of one type as if it were a value of another type. Two examples of this first usages are:

    1.1. Given that class B extends class A, you can ask for myB an instance of B to be treated as an instance of A by writing ((A) myB) wherever a reference to an instance of A could appear. This doesn't actually produce a new instance of A.

    1.2. Pre-Java5 collections stored all content as Object; this usually required you to use a cast after retrieving an object from a collection. For example, if you had stored a String in a Map and needed to get its length, you'd write something like ((String) myMap.get(someKey)).length() where the cast would be required in order to call the length method of String. Again, this doesn't cause a new String to be created.

  2. Explicitly converting one type to another (i.e. explicitly changing the representation). An example of this second usage is in the expression ((int) (float_var + 0.5F)) which rounds a floating-point variable by adding 0.5 (which produces a floating-point value) and then explicitly converting that value to an integer. The resulting integer value (after the (int) cast) is produced from the other value by internal computation.

Casting can be done when there's a superclass/subclass or interface/implementor relationship (meaning 1 above) or when the two types are primitive numeric types (meaning 2). You might look up "widening" and "narrowing" for more detail.

Boxing refers to wrapping primitive types in container objects, usually only done when you must have an object (e.g. storing a value in a collection). The primitive and wrapper types come in pairs:

int      Integer
long     Long
boolean  Boolean
...      ...

Unboxing simply means retrieving the primitive value from within its object wrapper.

As of Java5, when you write an expression that uses a primitive value where the corresponding wrapper type would be required (such as putting an integer into a collection), the compiler automagically slips in the code that actually wraps that primitive value. Likewise it will provide the unwrapping code for you.

So instead of writing (in pre-Java5) something like:

Map myMap = new HashMap();
...
myMap.put(someKey,Integer.valueOf(3));
...
int nextValue = (myMap.get(someKey)).intValue() + 1;

you can write:

Map<KeyType,Integer> myMap = new HashMap<KeyType,Integer>();
...
myMap.put(someKey,3);
...
int nextValue = myMap.get(someKey) + 1;

and the boxing/unboxing code is inserted by the compiler.

伊面 2024-07-20 10:17:55
List<String> list = (List<String>)object;

是一个演员。

void doSomething(Integer i) { ... }
...
doSomeething(5);

是自动装箱。

Integer getSomething();
...
int i = getSomething();

是自动拆箱。

List<String> list = (List<String>)object;

is a cast.

void doSomething(Integer i) { ... }
...
doSomeething(5);

is auto-boxing.

Integer getSomething();
...
int i = getSomething();

is auto-unboxing.

别理我 2024-07-20 10:17:55

Java 5 中引入了自动装箱,以防止出现以下代码:

map.put("ABC", new Integer(5));
map.put("DEF", new Integer(6));

您现在可以说:

map.put("ABC", 5);

虽然它更容易 - 如果您不完全确定自己在做什么,它确实有一些陷阱。

Autoboxing was introduced in Java 5 to prevent code such as :

map.put("ABC", new Integer(5));
map.put("DEF", new Integer(6));

You can now say :

map.put("ABC", 5);

Whilst its easier - it does have a few pitfalls if you aren't completely sure of what you are doing.

南街九尾狐 2024-07-20 10:17:55

装箱是将值包装在容器内,例如将 int 原始值包装在 Integer 对象内。

强制转换只是如何查看类型。

前者产生另一种值,后者只是修改如何处理已经存在的值,

除了基本类型之间的转换实际上会修改它们的表示形式。 (这并没有让事情变得更清楚,不是吗?)

Boxing is wrapping a value inside a container, such as an int primitive value inside an Integer object

Casting is just how to look at the type.

The former produces another kind of value, the later just modifies how to treat an already existing value

Except casting between primitive types actually modifies their representation. (This doesn't make it clearer does it?)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文