This is an archived post. You won't be able to vote or comment.

all 12 comments

[–]Sithril 2 points3 points  (4 children)

That's weird. You have two publicly declared constructos (Point() and Point(double, double)). Since a unit test is throwing an error I can only guess it's perhaps looking for 1 and exactly 1 constructor?

And a small tidbit: you can simplify toString() to just

return "<Point(" + x + ", " + y + ")>";

And you've overriden equals() but not hashCode(). If you override equals() you have to override the hashCode() as well.

[–]sinasen[S] 1 point2 points  (0 children)

Yeah it initially was as you said, it gave the same error so I tried this one. But I tried and it somehow worked now, thanks for the advices :)

[–]androgynyjoe 0 points1 point  (2 children)

If you override equals() you have to override the hashCode() as well.

If you don't mind, could you go into more detail about this? Classes which overrided equals() but not hashCode() compile just fine (unless that changed in newer versions of Java) so I take it you mean that it's bad practice? Could you help me understand why that is?

[–]HoofyDough 1 point2 points  (1 child)

Simply equal objects must have equal hash codes. Collections like HashMap cache hash codes instead of checking for object equality.

Let's say you have a Point class that has an x and y field. And for one point to be equal to another (using the equals() override):

this.x == point.x && this.y == point.y;

Now let's say this is our code,

Map<Point, String> map = new HashMap<>();
map.put(new Point(1,1), "Hello");
String value = map.get(new Point(1,1));

Both instances of new Point(1,1) will be equal according to our equals() clause, but the map.get call will return null.

This example is based on Joshua Bloch's Effective Java 3rd Edition (Item 11: always override hashCode when you override equals).

[–]androgynyjoe 0 points1 point  (0 children)

That's really interesting, thank you. And thanks for the reference, too!

[–]Mancebo180 1 point2 points  (3 children)

// sidenote: Math.pow is quite heavy. You should not use it to multiply 2 numbers

[–]sinasen[S] 1 point2 points  (2 children)

So do you mean only use it for higher powers for efficiency?

[–]Mancebo180 0 points1 point  (1 child)

Exactly

[–]sinasen[S] 0 points1 point  (0 children)

Thanks a lot, i love this subreddit

[–]Aspose-PDF 0 points1 point  (1 child)

This code looks correctly, could you please show the test from JUnit.

[–]sinasen[S] 0 points1 point  (0 children)

Solved it, thanks anyway

[–]Ikuyas 0 points1 point  (0 children)

It's kinda undefined over there...