I feel like i got some idea about wrapper classes. My question is when 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 The EmployeeWrapper contains the Employee object and implements or extends Attendee
The second source gives you a list of Customer objects
3.1 The CustomerWrapper contains the Customer object and implements or extends Attendee
The third list gives you a list of VendorContact objects
4.1 The VendorWrapper contains the VendorContact object and implements or extends Attendee
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.
Related
I'm having some trouble with the two variables: int and Integer.
They're roughly the same, but (as shown in the code below) they don't always act the same.
Here's my problem:
This piece of code works just perfect. I've made a generic method, printArray which needs an array of any kind of variable (since it is generic) in order to work.
Here I use the variable type Integer.
But, when I change my type of array 'getal' to int (instead of Integer), the method printArray doesn't work annymore. Why is that? Do generic methods not work with int type variables?
package Oefenen;
public class printArray
{
public static void main (String args[])
{
Integer[] getal = {10, 20, 30, 40, 50};
printArray(getal);
}
public static <E> void printArray (E[] intArray)
{
for (E element : intArray)
{
System.out.printf("%s\n", element);
}
}
}
ps: If I change the generic method to a method only for int's, it does work.
So I was thinking the problem is : Generic methods do not work with int's.
Am I
Generic methods only work with subtypes of Object. Integer is a sub type of Object. int is not an object but a primitive. So this is expected behaviour. This link is quite useful
This related question may also be useful
Generics works only for classes. int, as double, float, etc... are not classes
Generics work only for real Types, int is a primitive type (like float, double, ...)
You may, however, use autoboxing, e.g.
int primitiveInt = 1;
// this will 'autobox' (transform) the primitive type to a real type.
Integer typedInt = primitiveInt;
The other way around works, too, but be aware of possible NullPointerExceptions, because a real type may be null, which is not handled by autoboxing. (a primitive type has always a default value)
- Though Generic can be used with class, methods, variables, interface but one of the main reason of using Generics is to make Collection Type-Safe.
- Generics deals with only Objects. int is a primitive type, but Integer are Wrapper Objects. Due to AutoBoxing which was introduce from Java 5, you are not able to find the difference while you move from int to Integer or vice-versa.
- In Collection also when we use Generics, then Wrapper objects are used.
In java API documentation, it is written that Boolean wrapper class have 3 fields. True, False and Type.
For Type they have given description that:
TYPE: The Class object representing the primitive type boolean.
I can't understand what is this "type" field for?
Every Java class is represented in a running Java program by an object of type java.lang.Class, which, amongst other things, lets you perform reflective operations upon objects of that type. You can normally get to an object's Class by calling obj.getClass(), or by specifying its name explicitly, eg. String.class.
Primitive types, like int and boolean, don't have a class to represent them. But there are situations where it would be appropriate to have a Class object for them, and the TYPE members of the wrapper class types (like java.lang.Integer and java.lang.Double) represent exactly these Class objects.
You might be given one if you perform reflective operations on, say, an array of booleans, like this:
boolean[] bools = new boolean[1];
Class<?> c = bools.getClass().getComponentType();
Assert.assertEquals(Boolean.TYPE, c); // passes!
Note that the primitive boolean class is NOT the same as the Boolean wrapper class! That is,
Assert.assertNotSame(Boolean.TYPE, Boolean.class); // passes!
TYPE is a Class<Boolean> compile-time constant of the Boolean wrapper class representing the primitive type (boolean) the Boolean class wraps around.
The same is in all object wrappers: they all have a TYPE constant representing their primitive counterpart (e.g. Integer.TYPE).
It is used in the reflection API, to represent the type of a boolean argument or return type of a method, or the type of a field of a class.
I am a beginner in java. Sometimes I saw a method would return a int type, sometimes a string type, I want to how many arguments type in java.
for example:
I create a method:
public int dog(int i, String j , double k);
Could all the primitive types and reference types be used in the bracket ?
The answer is: Infinite.
There is no limit. Depending on what classes you write and what you want to do with the language, your functions can take any number of argument types and return any valid class type you write. Since you can write these classes until you run out of ideas, there is no limit.
For example: I can write a Dog class and do this:
public Dog getDog() {
return new Dog();
}
Dog isn't a primitive type. But it's still valid. I can make as many of these valid classes as I like.
A method can return any primitive or any Object. All classes in Java by default extends from Object. So there is no concrete answer to your question.
Practically everything in java is an object and every object has a type. You can create new objects with any kind of abstract type that comes in your mind.
User Defined Types and Primitive Types can passed as parameter for method. Similarly the return could be any type or even void.
I'm having some trouble with the two variables: int and Integer.
They're roughly the same, but (as shown in the code below) they don't always act the same.
Here's my problem:
This piece of code works just perfect. I've made a generic method, printArray which needs an array of any kind of variable (since it is generic) in order to work.
Here I use the variable type Integer.
But, when I change my type of array 'getal' to int (instead of Integer), the method printArray doesn't work annymore. Why is that? Do generic methods not work with int type variables?
package Oefenen;
public class printArray
{
public static void main (String args[])
{
Integer[] getal = {10, 20, 30, 40, 50};
printArray(getal);
}
public static <E> void printArray (E[] intArray)
{
for (E element : intArray)
{
System.out.printf("%s\n", element);
}
}
}
ps: If I change the generic method to a method only for int's, it does work.
So I was thinking the problem is : Generic methods do not work with int's.
Am I
Generic methods only work with subtypes of Object. Integer is a sub type of Object. int is not an object but a primitive. So this is expected behaviour. This link is quite useful
This related question may also be useful
Generics works only for classes. int, as double, float, etc... are not classes
Generics work only for real Types, int is a primitive type (like float, double, ...)
You may, however, use autoboxing, e.g.
int primitiveInt = 1;
// this will 'autobox' (transform) the primitive type to a real type.
Integer typedInt = primitiveInt;
The other way around works, too, but be aware of possible NullPointerExceptions, because a real type may be null, which is not handled by autoboxing. (a primitive type has always a default value)
- Though Generic can be used with class, methods, variables, interface but one of the main reason of using Generics is to make Collection Type-Safe.
- Generics deals with only Objects. int is a primitive type, but Integer are Wrapper Objects. Due to AutoBoxing which was introduce from Java 5, you are not able to find the difference while you move from int to Integer or vice-versa.
- In Collection also when we use Generics, then Wrapper objects are used.
I have read that in order to access the call object representing a primitive type, I can do this:
Class intClass = int.class;
But how do primitive types have classes to represent them? They are primitive, which should mean they have no class. Why does the example above work, and what class contains int (Integer class maybe)?
As the javadoc for the Class class states
Instances of the class Class represent classes and interfaces in a
running Java application. An enum is a kind of class and an annotation
is a kind of interface. Every array also belongs to a class that is
reflected as a Class object that is shared by all arrays with the same
element type and number of dimensions. The primitive Java types
(boolean, byte, char, short, int, long, float, and double), and the
keyword void are also represented as Class objects.
A Class object simply provides some metadata and factory methods for the type it represents.
For example, Class#isPrimitive() will tell you if the represented type is a primitive.
The class Class and its instances are, among other things, used for reflection.
Let's say you had the a class like
public class Example {
public long add(int first, long second) { // for whatever reason
return first + second;
}
}
and you wanted to invoke the add method, given only its name and parameter types. The following would fail
Class<?> exampleClass = Example.class;
exampleClass.getMethod("add", Integer.class, Long.class);
because the parameter types are not Integer and Long, they are int and long.
You'd have to do something like
Class<Example> exampleClass = Example.class;
Method addMethod = exampleClass.getMethod("add", int.class, long.class);
Example instance = exampleClass.newInstance();
addMethod.invoke(instance, 42, 58L);
If you look at the field summary for the Integer class, you will find that the primitive type int is actually represented by the class instance TYPE. Therefore, int.class would equal Integer.TYPE.
Here's a link to Javadocs where you can find the TYPE class instance.
When you type int.class you get the corresponding object wrapper class, which every primitive has. Read the Java tutorials on autoboxing for more information, and to see each primitive's corresponding wrapper class.