从 HashCode 获取值 Java

Get value from HashCode Java

我正在尝试创建一个函数,该函数使用 BasicAsteroid 类型的 (x, y, velocity x, velocity y) 值创建随机小行星,这是创建随机小行星的构造函数和函数:

private double x, y;
private double vx, vy;

public BasicAsteroid(double x, double y, double vx, double vy) {
    this.x = x;
    this.x = y;
    this.vx = vx;
    this.vy = vy;
}

public static BasicAsteroid makeRandomAsteroid() {
    Random rand = new Random();
    BasicAsteroid x = new BasicAsteroid((rand.nextInt()%FRAME_WIDTH), (rand.nextInt()%FRAME_HEIGHT), (rand.nextInt()%MAX_SPEED), (rand.nextInt()%MAX_SPEED));
    System.out.println(x);
    return x;
}

但是这是我创建小行星时的输出:

game1.BasicAsteroid@6773120a

game1.BasicAsteroid@4261b6b3

game1.BasicAsteroid@2673b915

game1.BasicAsteroid@113eb90b

game1.BasicAsteroid@1abcc522

如何输出值而不是 class@hashcode?

谢谢。

覆盖toString()方法

@Override
public String toString(){
     return "Asteroid at "+x+" "+y+" velocity "+vx+" "+vy;
}

您需要覆盖 class 上的 toString() 方法。

@Override
public String toString(){
    return "x: "+this.x+"y: "+this.y+"vx: "+this.vx+"vy: "+this.vy
}

在java中,当您打印一个对象时,它的toString() 方法被调用以创建将被打印的字符串。您在这里看到的是默认 toString 方法的输出。如果您想很好地打印这些值,请添加如下函数:

@Override
String toString(){
    return "Asteroid with coords: (" + x + ", " + y + "), velocity: (" + vx + ", " + vy + ")";
}