java - Comparable with doubles -


suppose class point2d has been defined storing 2-dimensional point x , y coordinates (both doubles). class includes following members:

enter image description here

your task modify class comparable adding appropriate compareto method. points should compared relative distance origin, points closer origin considered "less" points farther it. distance between 2 points defined square root of sum of squares of differences between x , y coordinates.

i'm unsure on how implement compareto method when there double. integers , strings use following syntax:

public int compareto(object name) {     // comparing integers     if (this.object != other.object) {         return this.field - other.field;     } else { // comparing strings         return tostring().compareto(other.tostring());     } } 

is there generalized implementation strategy when comparing between 2 doubles, currency or point class above?

use int double.compare(double d1, double d2).

you should not this.field - other.field, since may return incorrect result in case of numeric overflow. use int integer.compare(int x, int y).