小编Den*_*nis的帖子

Java HashMap containsKey始终为false

我有一个有趣的情况,我存储了Coordinate一个HashMap<Coordinate, GUIGameField>.

现在,关于它的奇怪之处在于,我有一段代码,应该保护,不应该使用两次坐标.但是,如果我调试此代码:

if (mapForLevel.containsKey(coord)) {
    throw new IllegalStateException("This coordinate is already used!");
} else {
    ...do stuff...
}
Run Code Online (Sandbox Code Playgroud)

... containsKey总是返回false,虽然我将一个哈希码为9731的坐标存储到地图中,当前的坐标也有哈希码9731.

之后,mapForLevel.entrySet()看起来像:

(java.util.HashMap$EntrySet) [(270,90)=gui.GUIGameField@29e357, (270,90)=gui.GUIGameField@ca470]
Run Code Online (Sandbox Code Playgroud)

我可能做错了什么?我没有想法了.谢谢你的帮助!

public class Coordinate {
    int xCoord;
    int yCoord;

    public Coordinate(int x, int y) {
        ...store params in attributes...
    }

    ...getters & setters...

    @Override
    public int hashCode() {
        int hash = 1;
        hash = hash * 41 + this.xCoord;
        hash = hash * 31 + this.yCoord; …
Run Code Online (Sandbox Code Playgroud)

java contains hashmap

2
推荐指数
1
解决办法
3083
查看次数

代码约定 - 捕获异常的好或坏做法,而不是之前的if-checking?

我想设置Integer一个特定的值,即0或在另一个类中找到的属性.由于该类的实例存储在MapListS,但这个地图可以在点为空,我不知道它的两种方式来处理这个更好.

Integer value = 0;
if (myMap != null && 
    myMap.get(keyForList) != null && 
    myMap.get(keyForList).get(0) != null) {
    value = myMap.get(keyForList).get(0).getAttribute();
}
Run Code Online (Sandbox Code Playgroud)

或者我认为更好,更有效的方式:

Integer value = 0;
try {
    value = myMap.get(keyForList).get(0).getAttribute();
} catch (NullPointerException e) {
    // without doing anything value is 0 as expected 
}
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

java coding-style exception-handling nullpointerexception

2
推荐指数
1
解决办法
1142
查看次数

使用 JavaFX 创建六边形字段

我的目标是创建一个六边形瓷砖领域。我已经有了一个细胞矩阵,每个矩阵都足够高以适合完整的六边形图像:

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class UITest extends Application {
    final private static String TILE_IMAGE_LOCATION = System.getProperty("user.dir") + File.separatorChar +"resources"+ File.separatorChar + "blueTile.png";
    final private static Image HEXAGON_IMAGE = initTileImage();

    private static Image initTileImage() {
        try {
            return new Image(new FileInputStream(new File(TILE_IMAGE_LOCATION)));
        } catch (FileNotFoundException e) {
            throw new IllegalStateException(e);
        }
    }
    public void start(Stage primaryStage) {
        int height = 4;
        int width = 6; …
Run Code Online (Sandbox Code Playgroud)

javafx hexagonal-tiles

2
推荐指数
1
解决办法
1994
查看次数