equals
假设一种合理的方法,这可以按照您的预期工作,使用单行。
(我通过 aLocation
而不是转换 a 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;
}
}