gpt4 book ai didi

java - 什么 Java 集合认为排列相等?

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:56 25 4
gpt4 key购买 nike

我想创建可能包含重复值且无特定顺序的集合。

换句话说:

{ 1, 1, 2 } == { 2, 1, 1 } == { 1, 2, 1 }

事实上,我想要一组这些集合,所以如果我尝试同时添加 { 1, 1, 2 }{ 2, 1, 1 } , 第二个 .add()实际上不会做任何事情。

是否有一个标准集合已经以这种方式运行?

如果我理解正确的话:

  • ArrayList 允许重复值,但有固定顺序
  • HashSet 允许任意顺序但没有重复值
  • TreeSet 确保顺序不变,但不允许重复值

是否有一个我忽略的集合允许重复值和任意或固定顺序,以便两个具有相同元素的集合被认为是相等的?


@asteri 询问了我的用例。在游戏中,我有不同长度的积木,可以首尾相接地放置以填补一定的距离。例如,如果距离为 10,则可以用 2-3-5 或 5-2-3 或 3-3-4 或 3-4-3 或任意数量的其他排列来填充。根据可用的 block ,我想列出所有可能的集合,以解决填补空白的问题。


自定义解决方案
@sprinter 建议创建 ArrayList 的子类。 @dasblinkenlight 和@Dici 建议使用 Map 来存储 { Element : Count }条目。我选择结合这两个建议。下面是 TreeMap 的子类。键总是以相同的顺序存储,以确保 hashCode() 方法产生相同的值,例如具有相同键和值的实例。

我用过 increment方法可以很容易地添加新出现的特定整数“值”。

package com.example.treematch;

import java.util.Map;
import java.util.TreeMap;

public class TreeMatch<K> extends TreeMap<K, Integer> {

@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}

if (!(other instanceof TreeMatch)) {
return false;
}

TreeMatch otherMatch = (TreeMatch) other;
if (size() != otherMatch.size()) {
return false;
}

for (Object key : this.keySet()) {
if (!otherMatch.containsKey(key)) {
return false;
}
}

for (Object key : otherMatch.keySet()) {
if (!this.containsKey(key)) {
return false;
}

if (this.get(key) != otherMatch.get(key)) {
return false;
}
}

return true;
}

public void increment(K key) {
Integer value;

if (this.containsKey(key)) {
value = (this.get(key)) + 1;
} else {
value = 1;
}

this.put(key, value);
}


@Override
public int hashCode() {
int hashCode = 0;

for (Map.Entry entry : this.entrySet()) {
hashCode += entry.getKey().hashCode();
hashCode = hashCode << 1;
hashCode += entry.getValue().hashCode();
hashCode = hashCode << 1;
}

return hashCode;
}
}

最佳答案

Java 内置库中没有任何内容,但 Guava 的 Multiset这样做。

关于java - 什么 Java 集合认为排列相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27831718/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com