gpt4 book ai didi

Java:比较两个类列表,无论顺序如何

转载 作者:行者123 更新时间:2023-12-01 09:35:21 25 4
gpt4 key购买 nike

如果您有两个类列表,如何比较它们以查看它们是否相同(无论顺序如何)。

Class[] list1[class1, class1, class2]
Class[] list2[class2, class1, class1]

无论顺序如何,这些列表都是相同的,但是 java 如何对其进行 boolean 运算呢?例如

if(list1.sort == list2.sort){}

最佳答案

最好的解决方案是添加 Guava并使用MultiSet .

HashMultiset<Class> hms1 = new HashMultiSet<>();
HashMultiset<Class> hms1 = new HashMultiSet<>();
for (Class c : list1) {
hms1.add(c);
}
for (Class c : list2) {
hms2.add(c);
}
if (hms1.equals(hms2) {
//lists are the same in your understanding of the same
}

更简单的解决方案是使用 Map<Class, Integer>

HashMap<Class, Integer> hm1 = new HashMap<>();
HashMap<Class, Integer> hm2 = new HashMap<>();
for (Class c : list1) {
if (!hm1.containsKey(c)) {
hm1.put(c, 1);
} else {
hm1.put(c, hm1.get(c)+1);
}
}
for (Class c : list2) {
if (!hm2.containsKey(c)) {
hm2.put(c, 1);
} else {
hm2.put(c, hm2.get(c)+1);
}
}
if (hm1.equals(hm2) {
//lists are the same in your understanding of the same
}

关于Java:比较两个类列表,无论顺序如何,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39016230/

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