什么是包装器类? 这样的类有什么用处呢?
当前回答
包装器类的出现是为了满足程序员的基本需求——即在只允许使用object的地方使用原始值。顾名思义,包装器类包装一个基本值,并将该值保存在Object中。因此,在所有不允许使用原语的地方——比如泛型、hashmap-key、数组列表等——程序员现在可以选择提供这些原语值作为相应的包装器类型。
此外,这些包装器类型有许多实用工具方法,用于从基本类型转换到相应的包装器类型和返回,以及从字符串转换到包装器类型和返回。
我在我的博客上写了一篇关于包装器类的详细文章,深入解释了包装器类型的概念——http://www.javabrahman.com/corejava/java-wrapper-classes-tutorial-with-examples/ (披露-这个博客是我所有的)
其他回答
一个包装类不一定需要包装另一个类。它可能是一个API类,在一个dll文件中包装功能。
例如,创建一个dll包装类可能非常有用,它负责所有dll的初始化和清理,并创建类方法来包装从GetProcAddress()创建的函数指针。
干杯!
包装器类是一个包装另一个类并提供客户端和被包装的原始类之间的抽象的类。
包装器类是唯一用于保存某些东西并向其添加一些功能的类。 在Java中,由于原语(如int,float,char…)不是对象,所以如果你想把它们当作一个对象,那么你必须使用包装类。 假设你想创建一个int型的Vector,问题是Vector只保存对象而不是原语。所以你要做的就是把所有的整型放在一个Integer包装器中并使用它。例子:
int number = 5;
Integer numberWrapped = new Integer(number);
//now you have the int in an object.
//and this is how to access the int value that is being wrapped.
int again = numberWrapped.intValue();
包装器类提供了一种将基本类型用作对象的方法。对于每个原语,我们都有一个包装器类,比如,
int Integer
byte Byte
Integer和Byte是原语int和Byte的包装类。当您需要将原语作为对象使用时,有时会有限制,因此包装类提供了一种称为装箱/拆箱的机制。
下面的例子可以很好地理解这个概念
double d = 135.0 d;
Double doubleWrapper = new Double(d);
int integerValue = doubleWrapper.intValue();
byte byteValue = doubleWrapper.byteValue();
string stringValue = doubleWrapper.stringValue();
这就是方法,我们可以使用包装器类类型转换成其他基本类型。当您需要将原语类型转换为对象并使用它们来获取其他原语时,就会使用这种类型的转换。但是对于这种方法,您需要编写一个大代码。但是,使用简单的强制转换技术也可以实现同样的效果,代码片段如下所示
double d = 135.0;
int integerValue = (int) d ;
虽然double值显式转换为整数值,也称为向下转换。
In general, a wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or component. These are useful by providing a level of abstraction from the implementation of the underlying class or component; for example, wrapper classes that wrap COM components can manage the process of invoking the COM component without bothering the calling code with it. They can also simplify the use of the underlying object by reducing the number interface points involved; frequently, this makes for more secure use of underlying components.