Results 1 to 3 of 3
- 06-05-2011, 11:47 AM #1
Member
- Join Date
- Jun 2011
- Posts
- 1
- Rep Power
- 0
Best Practice wrt Boxing / Unboxing
Some people say that everything should be boxed.
So instead of using primatives like int, you should always use their wrappers.
But suppose I don't always want to copy references of my primatives into Hashtables and PriorityQueues etc.
I might need to store some integers in a big 3 dimensional array like this:
int[][][] arr = new int[64][64][64];
Surely using the Integer object for this would be madness, wouldn't it create a lot of overhead?
Unless that is if the compiller was able to automatically convert those Integer objects to ints, but does this really happen and if so how does it make that decision? Can I really be sure it will make the right choice?
- 06-05-2011, 11:58 AM #2
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,561
- Rep Power
- 11
Some people say that everything should be boxed.
Which people? And for what reasons?
One could make a case for a smalltalk-like "everything is an object" language (Sun bought LongView Technologies in 1997). But the Java we have is the Java we have and I can't see the gain in just not using some of the types it provides.
- 06-05-2011, 12:10 PM #3
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,605
- Blog Entries
- 7
- Rep Power
- 17
Note that the Integer class also caches some values for Integer objects; i.e. the value [0, 127] are kept in a cache and the method Integer.valueOf(int i) returns the same object over and over again for ints in the mentioned range. The choice what to autobox and to what wrapper type may not be intuitive; have a look at this cryptic example:
I find autoboxing a mixed blessing. In SmallTalk no primitives exist so this little problem doesn't exist in that language.Java Code:import java.util.ArrayList; import java.util.List; public class Autoboxing { public static void main(String[] args) { Object foo = new Long(0xcafebabedeadbeefL); List<Object> bars = new ArrayList<Object>(); bars.add(true ? (Long)foo : (Long)foo); bars.add(true ? (Long)foo : (Number)foo); bars.add(true ? (Long)foo : (Double)foo); bars.add(true ? (Long)foo : ((Long)foo).longValue()); System.out.print("== :"); for (Object bar : bars) System.out.print(" "+(foo == bar)); System.out.println(); System.out.print("equals:"); for (Object bar : bars) System.out.print(" "+foo.equals(bar)); System.out.println(); } }
kind regards,
JosWhen people rob a bank they get a penalty; when banks rob people they get a bonus.
Similar Threads
-
GUI - is this bad practice?
By keo in forum New To JavaReplies: 3Last Post: 05-01-2011, 12:40 PM -
Combo box trouble turning into a boxing match with java
By Embercloud in forum New To JavaReplies: 1Last Post: 01-05-2011, 03:46 PM -
Best practice for packaging add-ons
By Goose in forum Advanced JavaReplies: 2Last Post: 08-05-2009, 10:51 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks