如何在java中从两个数组中查找不常见的值

如何在java中从两个数组中查找不常见的值,java,Java,我可以使用if条件和== 但不能找到不寻常的我想得到独特的价值,请帮助我 要获得不寻常的值 公共值:3我得到了预期的输出 不常见值:1 2 4 5如何获取!=情况不妙 int a[] = {1,2,3}; int b[] = {3,4,5}; void commonValues(){ for(int i=0;i<a.length;i++){ for(int j=0;j<b.length;j++){ if (a[i]==b[j]){

我可以使用if条件和== 但不能找到不寻常的我想得到独特的价值,请帮助我 要获得不寻常的值

公共值:3我得到了预期的输出

不常见值:1 2 4 5如何获取!=情况不妙

int a[] = {1,2,3};
int b[] = {3,4,5};

void commonValues(){
    for(int i=0;i<a.length;i++){
        for(int j=0;j<b.length;j++){
            if (a[i]==b[j]){
                System.out.println("Common values: "+a[i]);
            }
        }
    }
}
inta[]={1,2,3};
int b[]={3,4,5};
void commonValues(){
对于(int i=0;i您的代码是O(n^2),即对于大型阵列具有糟糕的性能特性

为了获得更好的性能,请使用
Set
而不是数组。
Set
然后提供了很好的辅助方法

下面是示例代码(有关集合运算符,请参见):


数组的排序是否与您的排序相同?数组中是否有重复的值?嗨,andreas,我声明要练习的两个数组,我需要将输出作为两个数组中的1 2 4 5个不同的值andreashi,andreas,在您的代码中设置方法抛出错误,例如1。参数2的修饰符非法。arr无法解析为变量3。cannot返回set请求更改,为什么使用此toSet方法将数组转换为set right声明HashSet无法更改时的计算是什么understand@RaviNarayananVarargs是在Java5中添加的,所以我不知道什么是“参数的非法修饰符”意思是,因为没有修饰符。--为什么我要设置
toSet
?因为没有内置的方法从
int[]
创建
Set
。我在上面的代码plz检查中添加了您的代码兄弟的整个图像
public static void main(String[] args) {
    int a[] = {1,2,3};
    int b[] = {3,4,5};

    Set<Integer> setA = toSet(a);
    Set<Integer> setB = toSet(b);

    // common = A ∩ B
    Set<Integer> common = new TreeSet<>(setA); // use TreeSet for sorted result
    common.retainAll(setB); // intersection: ∩
    System.out.println("common: " + common);

    // uncommon = (A ∪ B) \ common
    Set<Integer> uncommon = new TreeSet<>(setA); // use TreeSet for sorted result
    uncommon.addAll(setB); // union: ∪
    uncommon.removeAll(common); // asymmetric difference: \
    System.out.println("uncommon: " + uncommon);
}
private static Set<Integer> toSet(int... arr) {
    Set<Integer> set = new HashSet<>(arr.length * 4 / 3 + 1);
    for (int v : arr)
        set.add(v);
    return set;
}