有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java创建一个以集合为键的映射?

是否可以创建键为集合(任何种类的集合)的映射

如果我在最常见的收藏上试用,我会被告知该收藏无法与之媲美

我一直在尝试为自定义集合编写一个compareTo函数,但我正在努力

要么我需要将compareTo写入,要么我需要找到一个接受集合/由映射接受的集合的预制映射

如何将集合用作地图上的键?我已经查看了堆栈溢出,并在谷歌上搜索了好几次这个问题,但我从来没有找到一个可靠的解决方案


我想这样做的原因是,我已经用Java编写了一个模拟洗牌的“洗牌”模拟。我希望能够计算出特定的手(建模为集合)出现的次数。它看起来像这样:

   H4,C3,D2: 8  
   H9,D6,S11: 10  
   ......

共 (2) 个答案

  1. # 1 楼答案

    是的,您可以使用任何集合作为密钥。如果你想要一个像树形图这样的分类图,你必须提供一个比较器来确定顺序。但是,如果您使用任何类型的HashMap,您都不需要

    Map<List<Integer>, String> map = new HashMap<>();
    map.put(Arrays.asList(1,2,3), "one to three");
    map.put(Arrays.asList(7,8,9), "seven eat nine");
    System.out.println(map);
    

    印刷品

    {[1, 2, 3]=one to three, [7, 8, 9]=seven eat nine}
    
  2. # 2 楼答案

    Is it possible to create a map where the key is a Collection (any sort of collection)?

    是的,这是可能的,但绝对不推荐。如果您的集合发生更改,则其哈希代码可能也会更改,这可能会导致令人惊讶的行为

    Map's javadoc

    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.


    If I try it on most common collections I'm told the collection can't be cast to comparable.

    该键不需要具有可比性,除非使用已排序的映射,即TreeMap。使用一个简单的HashMap,你就不会有问题了


    编辑之后,我将创建一个新的不可变手类:

    class Hand implements Comparable<Hand> {
        private final List<Card> cards;
        Hand(Card c1, Card c2, Card c3) {
            cards = Collections.unmodifiableList(Arrays.asList(c1, c2, c3));
        }
        //getters, no setters
        //implement compareTo
    }
    

    如果您想在TreeSet<Hand, Integer>中使用compareTo,可以实现compareTo,例如手动排序