Java 5 wonderments
Hey,
1. Autoboxing - I could not get why do I need to use the Integer.valueOf(int)
method when I have auto unboxing. Why the autoboxing \ unboxing and the Integer.valueOf(int)
were added together to Java 5 and does the autounboxing also uses cache like the Integer.valueOf(int)
method?
2. Generics - What advantage do I have of using a non-bounded wildcard:
void printCollection(Collection<?> c){...}
instead of
void printCollection(Collection c){...}
Thanks.
> Why the autoboxing \ unboxing and
> the Integer.valueOf(int)
were added
> together to Java 5 and does the autounboxing also
> uses cache like the Integer.valueOf(int)
method?
The API docs for this method are pretty clear. And no, I don't think there's a need for caching the unboxing.
> 2. Generics - What advantage do I have of using a non-bounded wildcard:
In this case it prevents the method from adding something to the collection.
you use Integer.valueOf(int) when you need an Integer (Onject);
you use autoUNboxing when you need an (primitive) int. :--)
you can use valueOf(int) instead of autoboxing if you want to make clear that you want to make the boxing. Internally the compiler will call valueOf(int) to do the autoboxing.
[]
1) I don't know why you'd ever *need* to use Integer.valueOf(int) rather than relying on autoboxing. However, it's been in the API since the beginning and it would break a lot of code if it were removed.
Personally, I use it all the time because autoboxing is the devil.
2) I don't know if what the other poster said about not being able to add to the collection is true, but one reason you'd use <?> instead of just an unparameterized collection might be to explicitly let the compiler know that that's what you want, and thus avoid warnings.
jverda at 2007-7-12 16:37:49 >

1) Integer.valueOf(int) was added in JDK 5. That is the reason I asked - why did they add it along with auto unboxing. When should I use the method?
I agree that you need to think carefully when using autoboxing\unboxing because the JVM does conversions it is just automatic.
So you need to think before you do:
if (myInteger == 1 || myInteger == 5 || myInteger == 8) {..}
and do this instead:
int myInt = myInteger;
if (myInt == 1 || myInt == 5 || myInt == 8) {..}
2) There is no warnings when sending a generics collection to a method that gets an unparameterized collection.
I still don't get it.