+ 1

Why creating primitive wrapper objects is a bad idea??

Autoboxing over instantiating primitive wrapper objects

14th Jul 2020, 10:01 PM
Aaron
Aaron - avatar
5 Antworten
+ 3
Autoboxing is intuitive and requires less code. Character ch = 'a'; Vs Character ch = new Character('a'); Simple unboxing. char c = ch; But, you may not need to wrap your primitives if used in a way that doesn't make sense. Wrapping requires and consumes extra space in memory and likewise will slightly slow down you code during lookups and possibly conversions. However, when it is need to use a primitive like type with a data structure or method etc that uses Generics, a type that inherits from the Object class is required. So, it's not a bad idea to use primitive wrapper classes, bit you also should only use them when needed and when needed and possible use autoboxing/unboxing in lieu of more verbose and possibly less intuitive code. https://stackoverflow.com/questions/27647407/why-do-we-use-autoboxing-and-unboxing-in-java https://crunchify.com/java-tip-wherever-possible-try-to-use-primitive-types-instead-of-wrapper-classes/
14th Jul 2020, 11:08 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
ChaoticDawg thank you so much I now see the point ...
18th Jul 2020, 9:19 AM
Aaron
Aaron - avatar
+ 2
I'd just use autoboxing Character ch = 'a';
18th Jul 2020, 4:58 PM
ChaoticDawg
ChaoticDawg - avatar
0
ChaoticDawg about the example you used earlier.. on Character ch = new Character("a"); And Character ch = a; Which one is the best to go around ?
18th Jul 2020, 9:57 AM
Aaron
Aaron - avatar
0
Ohhk... So that you avoid creating objects in memory that already exist.
18th Jul 2020, 7:32 PM
Aaron
Aaron - avatar