equals
これは、妥当な方法を想定して、1行を使用して期待どおりに機能します。
(私Location
はを変換する代わりにを渡しDirection
ますが、メカニズムは同じです。)
public class Main {
private Location loc = new Location(0, 0);
public boolean move(Location newLoc) {
return !loc.equals(loc = newLoc);
}
public static void main(String[] args) {
Main m = new Main();
// Not same; moved from 0, 0: true--move successful.
System.out.println(m.move(new Location(42, 69)));
// Same; moved from 42, 69: false--move failed.
System.out.println(m.move(new Location(42, 69)));
// Not same; moved from 42, 69, 0: true--move successful.
System.out.println(m.move(new Location(69, 42)));
}
}
これは単純なLocation
実装を使用します。equals
IntelliJによって自動生成されたに注意してください。
public class Location {
private int x;
private int y;
public Location(int x, int y) {
this.x = x;
this.y = y;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Location location = (Location) o;
if (x != location.x) {
return false;
}
if (y != location.y) {
return false;
}
return true;
}
}