java - 在列表、 boolean 映射中存储值时出现比较错误

标签 java swing

我有一个用 Java 实现的完全可用的 MineSweeper 版本。但是,我正在尝试添加一个附加功能,该功能可以更新 map 以存储二维数组中地雷位置的索引。例如,如果位置 [x][y] 拥有一个地雷,我将存储一个包含 x 和 y 的链接列表,该列表映射到一个 boolean 值,该 boolean 值为 true 表示该空间拥有一个地雷。 (这个功能看似微不足道,但我这样做只是为了练习 Java 中的集合。)

我的相关私有(private)实例变量包括:

public Class World{ ...

private LinkedList<Integer>  index;

private Map<LinkedList<Integer>, Boolean> revealed;

“index”是要存储在 map 中作为每个 boolean 值的键的列表。

在我的构造函数中,我有:

 public World(){ ...

        tileArr = new Tile[worldWidth][worldHeight];
        revealed = new TreeMap<LinkedList<Integer>, Boolean>();
        index =  new LinkedList<Integer>();

        ... }

现在,在我放置地雷的方法中,我有以下内容:

 private void placeBomb(){
        int x = ran.nextInt(worldWidth);     //Random stream
        int y = ran.nextInt(worldHeight);    //Random stream

            if (!tileArr[x][y].isBomb()){
                tileArr[x][y].setBomb(true);

                index.add(x);                //ADDED COMPONENT
                index.add(y);
                revealed.put(index, true);
                index.remove(x);
                index.remove(y);             //END OF ADDED COMPONENT


            } else placeBomb();

    }

如果没有标记的添加组件,我的程序可以正常运行,并且我有一个完全可以运行的游戏。然而,这个添加给了我以下错误。

Exception in thread "main" java.lang.ClassCastException: java.util.LinkedList 
cannot be cast to java.lang.Comparable

如果有人能帮忙指出这个错误可能出在哪里,那将会非常有帮助!这仅用于对集合进行额外练习,而不是运行游戏所必需的。

最佳答案

这里实际上大约有3个问题。一个是您知道的,一个是您不知道的,第三个就是使用 LinkedList因为 map 的按键很笨重。

  1. ClassCastException发生的原因是 TreeMap 是一个排序集,要求其中的每个键都实现 Comparable接口(interface),否则你必须提供自定义ComparatorLinkedList没有实现Comparable ,所以你会得到一个异常(exception)。这里的解决方案可能是使用不同的 map ,例如 HashMap ,或者您可以编写自定义 Comparator.

    定制Comparator可能是这样的:

    revealed = new TreeMap<List<Integer>, Boolean>(
        // sort by x value first
        Comparator.comparing( list -> list.get(0) )
            // then sort by y if both x values are the same
            .thenComparing( list -> list.get(1) )
    );
    

    (我觉得有必要包括这个,这是一个更强大的示例,不依赖于特定索引处的特定元素):

    revealed = new TreeMap<>(new Comparator<List<Integer>>() {
        @Override
        public int compare(List<Integer> lhs, List<Integer> rhs) {
            int sizeComp = Integer.compare(lhs.size(), rhs.size());
            if (sizeComp != 0) {
                return sizeComp;
            }
            Iterator<Integer> lhsIter = lhs.iterator();
            Iterator<Integer> rhsIter = rhs.iterator();
            while ( lhsIter.hasNext() && rhsIter.hasNext() ) {
                int intComp = lhsIter.next().compareTo( rhsIter.next() );
                if (intComp != 0) {
                    return intComp;
                }
            }
            return 0;
        }
    });
    
  2. 您不知道的问题是您只添加了一个 LinkedList到 map :

    index.add(x);
    index.add(y);
    // putting index in to the map
    // without making a copy
    revealed.put(index, true);
    // modifying index immediately
    // afterwards
    index.remove(x);
    index.remove(y);
    

    这是未指定的行为,因为您将 key 放入,然后修改它。 Map 的文档对此有如下说法:

    Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map.

    实际发生的情况(对于 TreeMap )是您总是会删除以前的映射。 (例如,第一次调用 put 时,假设 x=0y=0 。然后下一次,您设置列表以便 x=1y=1 。这也会修改映射,这样当 put 被调用时,它会发现已经存在一个带有 x=1y=1 的键并替换映射。)

    因此,您可以通过说出以下任一内容来解决此问题:

    // copying the List called index
    revealed.put(new LinkedList<>(index), true);
    // this makes more sense to me
    revealed.put(Arrays.asList(x, y), true);
    

    但是,这引出了第三点。

  3. 如果您想练习集合,有更好的方法可以做到这一点。一种方法是使用 Map<Integer, Map<Integer, Boolean>> ,像这样:

    Map<Integer, Map<Integer, Boolean>> revealed = new HashMap<>();
    {
        revealed.computeIfAbsent(x, HashMap::new).put(y, true);
        // the preceding line is the same as saying
        // Map<Integer, Boolean> yMap = revealed.get(x);
        // if (yMap == null) {
        //     yMap = new HashMap<>();
        //     revealed.put(x, yMap);
        // }
        // yMap.put(y, true);
    }
    

    这基本上就像一个二维数组,但有 HashMap 。 (如果你有一个非常非常大的游戏板,这可能是有意义的。)

    从你的描述来看,听起来你已经知道你可以制作一个boolean isRevealed; Tile 中的变量类。

关于java - 在列表、 boolean 映射中存储值时出现比较错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43615717/

相关文章:

java - 简单日期格式设置为 01

java - 在 Java Web Start 中运行时,Swing Timer 不会停止触发事件

java - 在 JPanel 中绘制一个矩形,捕捉到最近的 x 像素

java - 如何在能够暂停/恢复的同时以固定间隔从线程获取字符串值?

尝试加载 opencv 时出现 java.lang.UnsatisfiedLinkError

java - 如何在 JavaFX css 中将 -fx-max-width 设置为 USE_PREF_SIZE?

java - 如何从 Eclipse 导出包含引用库的 jar 文件?

java - 使用 JSESSIONID cookie 的 servlet 中的 session 处理未获取 session

java - Netbean 中的 Jframe 形式

java - JButton 子类不改变透明度