java - How to subtract value from generic data -


i've defined point class this.

class point<e,f> {e x; e y; ...} 

so can give float, integer ... [anyway number]

but when want manipulate error.

void getdistance(point<number, number> pt) {     this.x-pt.x.floatvalue();   //not statement     this.y-pt.y.floatvalue(); } 

also should not give string type, should change number? or other way calculate distance generic type?

but if change type number how can specify different co-ordinate type [float or integer]?

how infer type here?

this.y-pt.y.typevalue? 

how can if integer or double?

when pass

pt.getdistance(otherpt);  

compiler shows error: create method getdistance(float,integer). how pass other point method?

try , define point this: point<e extends number, f extends number>. way compiler can tell e , f both numbers.

however, might want simplify point<n extends number> since both coordinates should of same type (i.e. double, integer etc.) - mixing types seems quite odd me.

the method have adjusted:

<x extends number, y extends number> float getdistance(point<x, y> pt) {   float dx = this.x.floatvalue() - pt.x.floatvalue();   float dy = this.y.floatvalue() - pt.y.floatvalue();    return (whatever distance calculation needs like); } 

note x , y might null, you'd have check that. specifying x , y here allow pass point<float, integer> point<double, long>'s member method. redefine e , f here, might source of confusion.

edit:

i'll elaborate bit on mark peters' comment:

using floatvalue() or doublevalue() might result in loss of precision, since double not able accurately represent each long value. might experience severe precision losses, higher numbers.

additionally, biginteger , bigdecimal numbers , have higher precision.

in order maximum precision, you'd have use bigdecimal in calculation , when creating initial values you'd have check types of values , call appropriate method:

  • for byte, short, integer , long you'd call bigdecimal.valueof( x.longvalue() )
  • for float , double you'd call bigdecimal.valueof( x.doublevalue() )
  • bigdecimal used is
  • biginteger passed bigdecimal constructor

this add quite bit of complexity , in case might want go arshajii's suggestion of subclassing point instead.


Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -