gpt4 book ai didi

java - 如何将数组与重复项作为集合进行比较?

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:30:19 25 4
gpt4 key购买 nike

我有两个可能重复的数组。我需要将它们作为集合进行比较。

例如 {1, 4, 9, 16, 9, 7, 4, 9, 11} 等同于 {11, 11, 7, 9, 16, 4, 1}。我尝试了很多方法,但我不断收到错误或错误的答案。这是我现在的代码:

import java.util.Scanner;
public class sameElement{
public static void main(String[] args){
int[] value1 = {11, 7, 9, 16, 4, 1};
int[] value2 = {11, 11, 7, 9, 16, 4, 1};
sort(value1);
sort(value2);
System.out.println(sameSet(value1, value2));

}
public static boolean sameSet(int[] a, int[] b){
int j = 0;
int counter2 = 0;
for(int i = 0; i < b.length; i++){
if(a[j] == b[i]){j++;}
else{counter2++;};}

}
public static int[] sort (int[] a){
for (int i = 0; i < a.length; i++) {
for (int i2 = i + 1; i2 < a.length; i2++){
if (a[i] > a[i2]){
int temp = a[i2];
a[i2] = a[i];
a[i] = temp;}
}
}
return a;
}
}

最佳答案

TreeSet 是一个排序集,因此它将免费执行您所需要的排序和重复删除。因此,您所要做的就是将数组加载到其中,然后使用 .equals()。

Integer[] value1 = { 11, 7, 9, 16, 4, 1 };
Integer[] value2 = { 11, 11, 7, 9, 16, 4, 1 };

Set<Integer> tSet1 = new TreeSet<Integer>(Arrays.asList(value1));
Set<Integer> tSet2 = new TreeSet<Integer>(Arrays.asList(value2));

System.out.println(tSet1);
System.out.println(tSet2);

System.out.println(tSet1.equals(tSet2));

输出

[1, 4, 7, 9, 11, 16]
[1, 4, 7, 9, 11, 16]
true

关于java - 如何将数组与重复项作为集合进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12524917/

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