Java集合与集合是否相等_Java集合认为排列是否相等?

我想创建可能包含重复值的集合,没有特定的顺序.

换一种说法:

{ 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或任何数量的其他排列填充.根据可用的块,我想列出所有可能解决的集合,填补空白.

定制解决方案

@sprinter建议创建ArrayList的子类. @dasblinkenlight和@Dici建议使用Map来存储{Element:Count}条目.我选择将这两个建议结合起来.下面是TreeMap的子类.密钥始终以相同的顺序存储,以确保hashCode()方法生成相同的值,例如使用相同的键和值.

我使用了一种增量方法,可以很容易地添加一个特定整数“值”的新出现.

package com.example.treematch;

import java.util.Map;

import java.util.TreeMap;

public class TreeMatch extends TreeMap {

@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;

}

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值