Use the Integer wrapper class?1 person found this helpful
Of course if you upgraded to Java 1.5 then the compiler would autobox the int to an Integer for you.
If you look at the docs for ArrayList, you'll see that add() takes an object. An int is not an object. It's a primitive, as are byte, short, char, long, float, double, and boolean. So you have to wrap the int in an object. The most appropiate object to use here is an Integer, as already indicated. If you upgrade to 1.5 or later (and you really should upgrade to 1.6, as even 1.5 is quite old now), then there's a new feature called autoboxing that takes care of wrapping and unwrapping primitives in their appropriate objects automatically for you.1 person found this helpful
Note that you're still not adding the int, but rather an Integer object that wraps it. You can write your code as if you're adding the int though, and the wrapping will happen automatically behind the scenes.
Thanks, everyone. I had a brainfart and didn't think about the primitive vs wrapper distinction. Wrapped it in an Integer & all is well.
(BTW, I cannot upgrade my java version. I'm writing plugins for a CAD PDM program, and am therefore stuck on 1.4.2)
Edited by: lkb3 on Jan 19, 2011 11:32 AM
It seems you are using older version of Java. Switch to latest version of Java as it support auto-boxing feature which allow you to add primitive data type like int , float in ArrayList. Also consider using Type Safe ArrayList instead of generic one.
Hope this helps.
user10808089, please have a look at the thread date. You're 2.5 years late.
Mod: locking this zombie.