当我们有包装类时,为什么支持原语? [英] When we have wrappers classes, why primitives are supported?

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

问题描述

我们在java中有包装类,比如Interger,Float ..为什么它仍然是支持java的原语,它停止java是完全面向对象的语言?

We have wrapper classes in java like Interger, Float.. why it is still supportng primitives which is stoppting java to be fully object oriented language?

推荐答案

作为对象的包装器被放置在堆中。基元只是值并进入堆栈。这样更有效,因为对于堆中的包装基元,您需要(至少)值(在堆栈中)对包装器对象的引用。

Wrappers, being objects, get placed in the heap. Primitives are just "values" and go in the stack. This is more efficient, because for wrapped primitives in the heap you need (at least) both the value (which is in the stack) and the reference to the wrapper object.

这种表现获益是否重要取决于你正在做什么。对于繁重的数字工作,当然,但99%的东西,这是一个烦恼。首先,你不能将原语存储在Collection中;他们得到了自动装箱。因此,存储大量数据的唯一方法是使用普通数组,这反过来会导致其他类型的低效率(例如,如果你需要调整它们的大小)。

Whether this performance gain matters at all depends on what you're doing. For heavy numerical work, definitely, but for 99 % of stuff out there, this is rather an annoyance. For one thing, you can't store primitives in a Collection anyway; they get autoboxed. So the only way to store lots of them is to use plain arrays, which in turn can lead to other kinds of inefficiencies (if you need to resize them, for instance).

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

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