Java:为什么需要包装类? [英] Java: Why are wrapper classes needed?

查看:153
本文介绍了Java:为什么需要包装类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在很高的层次上,我知道我们需要包装原始数据类型,例如int和char,通过使用它们各自的包装类在Java集合中使用它们。我想了解Java集合工作在低级别通过询问:为什么我们需要包装原始数据类型作为对象,以便能够使用它们在集合?我先感谢你的帮助。

解决方案

在虚拟机级别,这是因为与引用类型(如java.lang.Object及其派生类型)相比,基本类型在内存中的表示方式非常不同。 Java中的原始int例如在内存中只有4个字节,而一个对象本身占用至少8个字节,再加上4个字节来引用它。这样的设计是对CPU可以更有效地处理原始类型的简单反映。



因此,您的问题为什么需要包装类型的一个答案是因为



但是对于程序员来说,这种区别增加了一些不需要的认知开销(例如,不能在集合中使用int和float)。事实上,很可能通过隐藏这种区别来做一个语言设计 - 许多脚本语言做到这一点,而CLR这样做。从1.5开始,Java也是这样。这是通过让编译器在原始表示和对象表示之间静态插入必要的转换来实现的(通常被称为装箱/取消装箱)。



是,不,我们不需要它,因为编译器会为你自动,并在一定程度上你可以忘记在幕后发生了什么。


On the very high level, I know that we need to "wrap" the primitive data types, such as int and char, by using their respective wrapper classes to use them within Java collections.I would like to understand how Java collections work at the low level by asking:"why do we need to wrap primitive data types as objects to be able to use them in collections?"I thank you in advance for your help.

解决方案

At the virtual machine level, it's because primitive types are represented very differently in memory compared to reference types like java.lang.Object and its derived types. Primitive int in Java for example is just 4 bytes in memory, whereas an Object takes up at minimum 8 bytes by itself, plus another 4 bytes for referencing it. Such design is a simple reflection of the fact that CPUs can treat primitive types much more efficiently.

So one answer to your question "why wrapper types are needed" is because of performance improvement that it enables.

But for programmers, such distinction adds some undesirable cognitive overhead (e.g., can't use int and float in collections.) In fact, it's quite possible to do a language design by hiding that distinction --- many scripting languages do this, and CLR does that. Starting 1.5, Java does that, too. This is achieved by letting the compiler silently insert necessary conversion between primitive representation and Object representation (which is commonly referred to as boxing/unboxing.)

So another answer to your question is, "no, we don't need it", because the compiler does that automatically for you, and to certain extent you can forget what's going on behind the scene.

这篇关于Java:为什么需要包装类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆