Doubt in Wrapper class
I feel like i got some idea about wrapper classes. My question is wh开发者_StackOverflow社区en will a method expect object? only then we need to use wrapper classes right? generally a method expects some paratmeters like int add(int a); Is this "int a" a primitive value? example pls
The Java primitive types are int
, double
, byte
, boolean
, char
, short
, long
, and float
.
If a function signature wants int
, then you are passing it a primitive. If, for example, it wanted Integer
, it wants the wrapper class Integer
. In Java 1.5, autoboxing can take effect and automatically wrap primitives into its wrapper type. Unboxing can also take place, where a wrapper class is converted to its primitive equivalent for methods that expect primitives.
class Example
{
public static void usePrimitiveInt(int i) { }
public static void useIntegerClass(Integer i) { }
public static void main(String [] args)
{
int i = 5;
Integer iObj = 10;
Example.usePrimitiveInt(i); // use primitive
Example.useIntegerClass(i); // autobox int to Integer
Example.usePrimitiveInt(iObj); // unbox iObj into primitive
}
}
Remember that another name for the wrapper pattern is the adapter pattern.
One of the first examples of the wrapper pattern that we see in java are the primitive wrapper classes:
- java.lang.Integer wraps int
- java.lang.Character wraps char
- java.lang.Long wraps long
- etc.
These wrappers are useful when you need object representations of the primitives, for instance when you need to store them in a Collection.
Wrappers can be useful when you need to normalise a common interface across different classes, especially those that you cannot change because for instance they might be part of a 3rd party library.
For example, say you need to process a list of people that will be attending an event, however you may have multiple sources of information with their own representations of a person.
- Your processing method accepts a list of
Attendee
objects. - The first source gives you a list of
Employee
objects
2.1 TheEmployeeWrapper
contains theEmployee
object and implements or extendsAttendee
- The second source gives you a list of Customer objects
3.1 TheCustomerWrapper
contains theCustomer
object and implements or extendsAttendee
- The third list gives you a list of
VendorContact
objects
4.1 TheVendorWrapper
contains theVendorContact
object and implements or extendsAttendee
You now have a normalised representation of the different types of Attendee
objects.
You said you understand wrapper classes. Then there should be nothing to explain. The method expects a wrapper class when the method signature says it does. If the parameter type is Integer
, the method expects wrapper class. If int
, it expects primitive value.
精彩评论