检查两个数组是否按某种顺序具有相同的元素

时间:2015-02-16 22:02:50

标签: java arrays

用户需要键入两个数组(数组a和数组b),然后数组需要运行一个方法,以查看它们是否按某种顺序包含相同的元素,忽略重复。

我遇到了一些麻烦,我一直得到一个"找不到符号 - 方法包含(int [],int)"我的sameSet()方法中的错误。

有人能告诉我为什么会这样,并指出我正确的方向吗?

 /**
 * check whether two arrays have the same elements in some order, ignoring
 * duplicates. For example, the two arrays 1 4 9 16 9 7 4 9 11 and 11 11 7 9
 * 16 4 1 would be considered identical.
 */

 public static boolean sameSet(int[] a, int sizeA, int[] b, int sizeB) {
    boolean sameSets = true; 

    for (int i = 0; i < a.length; i++) {
        if (!contains(b, a[i])) { // This line right here is where I'm having trouble. I get "Cannot symbol - method contains (int[], int)" 
            sameSets = false;
        }
    }
    for (int i = 0; i < b.length; i++) {
        if (!contains(a, b[i])) { // This line also has the same problem as the above.
            sameSets = false;
        }
    }
    return sameSets;
}


// main method used to collect user input, then pass input to sameSet method

    public static void main() { 

    final int LENGTH = 10;
    int sizeA = 0;
    int sizeB = 0;
    int a[] = new int[LENGTH];
    int b[] = new int[LENGTH];

    Scanner input = new Scanner(System.in);
    Scanner in = new Scanner(System.in);

    System.out.println("Please fill up values for array a, Q to quit: ");
    while (input.hasNextInt() && sizeA < a.length) {
        a[sizeA] = input.nextInt();
        sizeA++;

    }

    System.out.println("Please fill up values for array b, type in Q to quit: ");
    while (in.hasNextInt() && sizeB < b.length) {
        b[sizeB] = in.nextInt();
        sizeB++;
    }
    for (int i : b) {
        System.out.print(i + " | "); // For testing

    }

   sameSet(a, sizeA, b, sizeB);

}

3 个答案:

答案 0 :(得分:1)

您可以从每个数组创建HashSet,然后使用set1.equals(set2)

答案 1 :(得分:0)

它说的是“包含”方法不存在。您的代码中没有“包含方法”。

答案 2 :(得分:0)

包含??? 按照我的说法,您需要声明此方法 或者需要使用其中'contains'作为有效操作提供的集合

更好的是根据您的要求使用套装