在 Java 中使用包装类而不是原语的好处

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13999309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:42:07  来源:igfitidea点击:

Benefits of using wrapper classes over primitives in Java

javawrapper

提问by veepsk

At a very abstract level I do know that wrapper classes, create an object of the primitive data type but I was curious as to why do we need to use wrapper classes and what benefits do they offer over primitive data types.

在一个非常抽象的层面上,我确实知道包装类创建了一个原始数据类型的对象,但我很好奇为什么我们需要使用包装类以及它们比原始数据类型提供什么好处。

回答by Evgeniy Dorofeev

Collections in the first place, for example,List<Integer>, you cannot use primitive inthere. Actually any generic class / interface that can work with different object types like

首先是集合,例如,在这里List<Integer>不能使用原语int。实际上任何可以使用不同对象类型的通用类/接口,例如

public interface Callable<V> {
    V call() throws Exception;
}

Note that wrapping is best done using not new Integer(i) but Integer.valueOf(i) the latter will try to use cache. Unwrapping is done as Integer.intValue(). These wrapping / unwrapping of primitives are so typical operations that Java 5 introduced autoboxing / unboxing

请注意,最好不要使用 new Integer(i) 而是使用 Integer.valueOf(i) 来完成包装,后者将尝试使用缓存。展开是作为 Integer.intValue() 完成的。这些原语的包装/解包是非常典型的操作,以至于 Java 5 引入了自动装箱/拆箱

List<Integer> list = new ArrayList<>();
list.add(1);
int i = list.get(0);

this code is automatically converted by Java compiler into

此代码由 Java 编译器自动转换为

list.add(Integer.valueIf(1));
int i = list.get(0).intValue();    // this is where NullPointerException sometimes happens

回答by JavaNewbie_M107

Wrapper classes are designed to add more functionality to the primitive types, so that they are compatible with generic code, using the Collection Framework, and many other benefits. However, they are not mean't to replaceprimitive types.

包装类旨在为基本类型添加更多功能,以便它们与泛型代码、使用集合框架和许多其他好处兼容。但是,它们并不是要替换原始类型。

So, you should use wrappers only when necessary, such as when dealing with generics, because creating an object adds substantial overheads to your program. So, in normal cases, you should stick to primitives.

因此,您应该仅在必要时使用包装器,例如在处理泛型时,因为创建对象会为您的程序增加大量开销。所以,在正常情况下,你应该坚持使用原语。

回答by Rich O'Kelly

A wrapper type enables a primitive to hold more contextual meaning. For instance an integer could be anything, whereas a class called Hours, for example, gives the number meaning wherever it is used.

包装器类型使原语能够保存更多的上下文含义。例如,一个整数可以是任何东西,而一个叫做 hours 的类,例如,在任何使用它的地方都给出了数字的含义。

They also enable methods to be written that mutate the said primitive in a consistent and obvious way to consumers. Have a look at Domain Driven Designfor more information surrounding this point.

它们还允许编写方法,以一致且显而易见的方式对所述原语进行变异。查看领域驱动设计以获取有关这一点的更多信息。

回答by Qiang Jin

The primitive types just hold value, the wrapper class gives it a name.

原始类型只保存值,包装类给它一个名字。

With a class name, the compiler can do some static check for you. It makes the interface more meaningful. And you can also defined some method in wrapper classes to validate the primitive values.

使用类名,编译器可以为您做一些静态检查。它使界面更有意义。您还可以在包装类中定义一些方法来验证原始值。

Normally, for a small project, i think use primitive types is just fine.

通常,对于一个小项目,我认为使用原始类型就可以了。

回答by Christian Ullenboom

Wrapper objects are normal objects and there references can be null. This allows the usage of a "not set" state which is impossible with primitives.

包装对象是普通对象,引用可以是null. 这允许使用原语不可能的“未设置”状态。

Integer no = null;    // not set

You have to use a magic value like -1 to indicate that a primitive variable is "unset".

您必须使用 -1 之类的魔术值来指示原始变量“未设置”。

回答by karthick

Just imagine : your playing a game in that you need to save the status and you want to play in different computer(same game) then u decided to take status (level) to the other computer then you can continue from that state(not from the beginning).. Okay come to the questions if your current weapons status is 3. like { int weapons=1; if(you add weapons by playing some levels okay now its 3) } but you cannot able to store it as object because primitives are different.(lives in stack). so you need weapons as objects (( solution : create Integer Object)) Integer weapon = new Integer(1){ ... }

试想一下:您玩游戏时需要保存状态并且您想在不同的计算机上玩(同一游戏)然后您决定将状态(级别)带到另一台计算机然后您可以从该状态继续(而不是从开始.. 好的,如果您当前的武器状态是 3,请回答问题。例如 { int Weapon=1; if(你通过玩一些关卡来添加武器,现在它的 3) } 但是你不能将它存储为对象,因为基元是不同的。(生活在堆栈中)。所以你需要武器作为对象((解决方案:创建整数对象))整数武器 = new Integer(1){ ... }