比较数组之间的所有元素和 return 所有可能的匹配项

Compare all elements between arrays and return all possible matches

我正在尝试创建一个函数,该函数将一个数组的所有元素与第二个数组的所有元素进行比较,并将 return 所有可能的匹配项,如果未找到匹配项,则会发出消息。当我尝试实现代码时,出现索引超出范围错误。内部 for 循环可能在外部 for 循环完成 运行 之前就已经用完了。如何修改才能避免这种情况的发生?

Stocks[] stockList3 = new Stocks[3];
stockList3[0] = new Stocks("a", 2, 1, "Buy");
stockList3[1] = new Stocks("a", 3, 1, "Buy");
stockList3[2] = new Stocks("a", 4, 1, "Buy");

Stocks[] stockList4 = new Stocks[3];
stockList4[0] = new Stocks("a", 2, 1, "Buy");
stockList4[1] = new Stocks("a", 5, 1, "Buy");
stockList4[2] = new Stocks("a", 4, 1, "Buy");

public void matching(Stocks[] array1, Stocks[] array2) {
    for (int i = 0; i < array1.length; i++) {
        for (int j = 0; i < array2.length; j++) {
            if (array1[i].stockPrice == array2[j].stockPrice) {
                System.out.println("It's a match at $" + array1[i].stockPrice);
            }
            System.out.println("still searching...");
        }
        System.out.println("first loop test...");
    }
}

在你的 j-loop 中你说的是 i<array2.length 而不是 j<array2.length

public void matching ( Stocks[] array1, Stocks[] array2){
    for (int i=0; i<array1.length;i++){

        for (int j=0;
                 j<array2.length;  //this j was an i
                 j++){

            if (array1[i].stockPrice == array2[j].stockPrice){
                System.out.println("It's a match at $" + array1[i].stockPrice);



            }
            System.out.println("still searching...");
        }
        System.out.println("first loop test...");   
    }

}

如果不使用两个 for loops,而是使用 Set 集合来存储一个数组中的一个 stockPrices,怎么样?

public static List<Stocks> matching(Stocks[] one, Stocks[] two) {
    Set<Integer> stockPrices = Arrays.stream(one)
                                     .map(stock -> stock.stockPrice)
                                     .collect(Collectors.toSet());
    return Arrays.stream(two)
                 .filter(stock -> stockPrices.contains(stock.stockPrice))
                 .collect(Collectors.toList());
}

它使用 O(n) 额外内存(其中 none.length) O(n + m) 执行时间(其中 mtwo.length).