问题
For example, look at this code:
Integer myInt = new Integer(5);
int i1 = myInt.intValue();
int i2 = myInt;
System.out.println(i1);
System.out.println(i2);
As you can see, I have two ways of copying my integer value from the wrapper to the primive:
I can use unboxing
OR
I can use the method intValue()
So... what's the need of having a method when there is already unboxing?
回答1:
Unboxing was introduced in Java 5. The wrappers (including this method) have been there since the original release.
A link to the Javadoc
In that time (1996) we did need the intValue()
method and as Oracle guarantees backward backwards compatibility... up to a certain level (it is not always 100% on major releases).
The method has to stay in.
回答2:
In addition to Frank's answer which gives a good historical perspective there is still a need to use the intValue()
today in some situations.
Be aware of the following pitfall that shows that you cannot regard an Integer
as an int
:
Integer i1 = new Integer(5);
Integer i2 = new Integer(5);
//This would be the way if they were int
System.out.println(i1 == i2); //Returns false
//This is the way for Integers
System.out.println(i1.intValue()==i2.intValue()); //Returns true
System.out.println(i1.equals(i2)); //Returns true
Returns
false
true
true
来源:https://stackoverflow.com/questions/15985928/what-is-the-need-of-an-intvalue-method-if-wrappers-use-unboxing