比较数组之间的所有元素并返回所有可能的匹配项

我正在尝试创建一个函数,将数组的所有元素与第二个数组的所有元素进行比较,并将返回所有可能的匹配项,如果未找到匹配项则返回消息。当我尝试实现代码时,我得到一个索引超出范围的错误。在外部 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...");

    }

}


慕妹3146593
浏览 112回答 2
2回答

侃侃无极

for loops使用Setcollection 来存储stockPrices数组中的一个而不是 two 怎么样?public static List<Stocks> matching(Stocks[] one, Stocks[] two) {&nbsp; &nbsp; Set<Integer> stockPrices = Arrays.stream(one)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(stock -> stock.stockPrice)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toSet());&nbsp; &nbsp; return Arrays.stream(two)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(stock -> stockPrices.contains(stock.stockPrice))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList());}它使用O(n)额外内存(其中n是one.length)和O(n + m)性能时间(其中m是two.length)。

函数式编程

在您的 j-loop 中,您说i<array2.length的是j<array2.lengthpublic void matching ( Stocks[] array1, Stocks[] array2){&nbsp; &nbsp; for (int i=0; i<array1.length;i++){&nbsp; &nbsp; &nbsp; &nbsp; for (int j=0;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;j<array2.length;&nbsp; //this j was an i&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;j++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (array1[i].stockPrice == array2[j].stockPrice){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("It's a match at $" + array1[i].stockPrice);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println("still searching...");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("first loop test...");&nbsp; &nbsp;&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java