Java 中的原始类型 [英] Primitives Types in Java

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

问题描述

为什么在java中使用原始类型而不是Wrapper类?我想知道我们已经在java中有包装类,那么为什么我们需要使用原始类型?java中原始类型的重要性是什么?

Why to use primitive types in java instead of Wrapper classes? I want to know that already we have wrapper classes in java, then why we need to use primitive types? What are the importance of primitive types in java?

推荐答案

你的问题倒退了.原始类型比它们的包装器更基础.

Your question is backwards. The primitive types are more fundamental than their wrappers.

包装器真正为您提供的唯一有用的东西是能够被视为 Object 的子类(以便它们可以放入集合等等).所有真正有用的东西(如算术和排序)都由原始类型提供.

Really the only useful thing that wrappers give you is the ability to be treated as a subclass of Object (so that they can be put into collections and so on). All the really useful stuff (like arithmetic and ordering) is provided by the primitive type.

请注意,虽然您可以这样说:

Note that while you can say stuff like:

Integer i = Integer.valueOf(4);
Integer j = Integer.valueOf(2);
Integer k = i + j;

这只是一种方便.在下面,最后一行变成了这样:

this is just a convenience. Underneath, the last line becomes something like:

Integer k = Integer.valueOf(i.intValue() + j.intValue());

这样算术就发生在原始值上.(这种便利称为装箱/拆箱.)这样做会降低性能,因此在我的机器上,此循环:

so that the arithmetic occurs on the primitive values. (This convenience is known as boxing/unboxing.) There is a performance penalty to this, so that on my machine, this loop:

for (int i=0; i<10000000; i++) { }

大约比这个循环快 10 倍:

is about 10 times faster than this loop:

for (Integer i=0; i<10000000; i++) { }

这篇关于Java 中的原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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