I have the following code in Python which I want to implement in Java but I have a problem when it comes to representing the array of elements of type double
a String
.
I have tried doing a 'casting' of the form return (String) this.coordinates();
, invoking the method .toString()
of the form return this.coordinates().toString();
and invoking the method .valueOf
of the form return String.valueOf(this.coordinates());
but none returns the expected output In the same way I have an error when returning the type boolean false
because if I compare two points that are equal returns me false
instead of the correspondingtrue
Input:
(10.0, 5.0);
Output:
(10.0, 5.0);
Python code
class Point2D:
def __init__(self, x: float, y: float):
self.__x = x
self.__y = y
def coordinates(self):
return (self.__x, self.__y)
def __eq__(self, other):
if type(other) == Point2D:
return self.coordinates() == other.coordinates()
else:
return False
def __str__(self):
return str(self.coordinates())
if __name__ == "__main__":
point1 = Point2D(10.0, 5.0)
point2 = Point2D(12.0, 5.0)
print(str(point1), str(point2), point1 == point2)
Java code
import java.util.Arrays;
public class Point2D {
protected double x, y;
public Point2D(double x, double y) {
this.x = x;
this.y = y;
}
public double[] coordinates() {
double[] result = {this.x, this.y};
return result;
}
@Override
public boolean equals(Object other) {
Point2D iterable = (Point2D)other;
if (other instanceof Point2D) {
return this.coordinates() == iterable.coordinates();
} else {
return false;
}
}
@Override
public String toString() {
return this.coordinates().toString();
//return String.valueOf(this.coordinates());
// return (String) this.coordinates();
}
The operator
==
is for comparing primitive data or references. If you want to compare the content of the array, you have to iterate over it and compare its elements, otherwise only if the reference is the same it==
will returntrue
.On the other hand, the method
toString()
of an array does not convert its content to a string. For that you could use Arrays.toString()In this case, when comparing two instances of the same class and being only two data, I would simply compare the values. Something like that: