我对编程有点新意,并希望尝试制作一个更难的盒式2d游戏用于学习然后我之前的游戏。唉,我还是新人,所以请愚蠢地回答你的答案,如果可能的话。
我现在一直在玩哈希地图几个小时,似乎无法弄清楚为什么喂我的钥匙不会给我它的价值。
package main;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return this.x;
}
public int getY() {
return this.y;
}
}
public Map<Point, Integer> Blocks = new HashMap<Point, Integer>();
int x = 0;
int y = 0;
while (active == true) {
Point Apple = new Point(x, y);
Blocks.put(Apple, 1);
if (x <= 800) {
x += 32;
} else {
x = 0;
y += 32;
}
if (y > 600) {
active = false;
}
}
MouseX = (Mouse.getX() / 32) * 32;
MouseY = (Mouse.getY() / 32) * 32;
Point rawr = new Point(MouseX, MouseY);
if (Blocks.containsKey(rawr)) {
y = Blocks.get(rawr);
}
结果是y = 0而不是y = 1。感谢您给予的任何帮助。
答案 0 :(得分:2)
你没有遵守最基本的java合同:.equals() / .hashCode()合同。
您需要在课程Point
中覆盖它们。这里有很多关于SO和网络的例子。
现在,为什么这适用于此,因为您尝试查看blocks
地图是否包含您已实例化的Point
。但是,您使用的HashMap
中的密钥严重依赖于.equals()
和.hashCode()
。 .contains(x)
当且仅当地图k
中有一个键k.equals(x)
时才会@Override
public int hashCode()
{
return 31 * x + y;
// If using Java 7, this can be:
// returns Objects.hash(x, y);
}
@Override
public boolean equals(final Object o)
{
// No object instance is equal to null
if (o == null)
return false;
// If the object is the same, this is true
if (this == o)
return true;
// If not the same object class, false
if (getClass() != o.getClass())
return false;
final Point other = (Point) o; // safe to cast since getClass() == o.getClass()
return x == other.x && y == other.y; // test instance member equality
}
。
对于你的班级:
{{1}}
答案 1 :(得分:0)
根本问题是您的Point
密钥对其equals
方法的语义错误。您正在使用从equals
继承的Object
方法,并且 方法表示如果两个对象是相同的对象,则它们是“相等的” - 如果它们是同一个对象的话。
因此,假设您创建(说)点实例为new Point(1,1)
并将其用作向哈希表添加条目的键。然后,当您想要在(1,1)
处查找点时,您可以创建第二个点实例(使用new Point(1,1)
)...并调用get(...)
。但是这个新点是不同的点对象(p1.equals(p2)
是'false'!)...所以查找失败。
解决方案是覆盖equals
课程中的Point
,以便两个Point
个对象“相等”,如果它们具有相同的x
和y
属性。您然后需要覆盖hashcode
,以便符合equals()
/ hashcode()
合同。
以下是一个例子:
//
// The fields are 'final' because we want make it clear that a Point
// is immutable. The class itself is 'final' to simplify the problem of
// testing for equality. (Equality between an instance of a class and
// an instance of a subclass can be problematic. If the subclass overrides
// the `equals` method you get in problems with the requirement that equality
// is symmetric; i.e. ensuring that 't.equals(st) == st.equals(t)'. Making
// Pint `final` removes that potential issue.)
//
public final class Point {
private final int x;
private final int y;
public Point(int x, int y) { this.x = x; this.y = y; }
public int getX() { return this.x; }
public int getY() { return this.y; }
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (!(other instanceof Point)) {
return false;
}
Point point = (Point) other;
return this.x = point.x && this.y == point.y;
}
public int hashcode() {
return this.x + 31 * this.y;
}
}