Friday 15 March 2013

java - Manipulating Generics through auto/unboxing -



java - Manipulating Generics through auto/unboxing -

public class generics { public static <t> t increasebalance (t amount){ //say want increment amount here, set finalbalance , homecoming homecoming finalbalance; } public static void main(string[] args){ system.out.println(increasebalance (new integer(10))); system.out.println(increasebalance (new double(20))); } }

hi. generics , auto/unboxing. in simple code segment, trying send 2 different objects increasebalance(t amount) method , increment amount 10 , homecoming final balance. how can achieved? create understanding of generics , auto/unboxing clearer. lot.

solution

this can technically done, , straight forwards @ that!

disclaimer:

you should never utilize double ( or worse float ) deal currency or currency domains precision errors can creep in , compound important errors in expected output. bigdecimal for! straw man example.

q26260792.java import javax.annotation.nonnull; public class q26260792 { private double = 42.0; public static void main(final string[] args) { final q26260792 q = new q26260792(); system.out.println(q.add(new short((short)1))); system.out.println(q.add(new integer(2))); system.out.println(q.add(new long(1000l))); system.out.println(q.add(new double(1.5))); system.out.println(q.add(new float(1.3))); } public <t extends number> double add(@nonnull final t n) { // n of type `number` no matter started out // original type lost after erasure homecoming + n.doublevalue(); } } outputs: 43.0 44.0 1042.0 43.5 43.299999952316284 notes:

having homecoming type t doesn't much result in precision of non-generic number , of type number; in illustration double since a , downwards cast number regardless.

this works because n ever number type after erasure, , number.doublevalue() guaranteed implemented on number subclasses.

java generics autoboxing unboxing

No comments:

Post a Comment