为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

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

2 回答

?
侃侃无极

TA贡献2051条经验 获得超10个赞

for loops使用Setcollection 来存储stockPrices数组中的一个而不是 two 怎么样?


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)额外内存(其中n是one.length)和O(n + m)性能时间(其中m是two.length)。


查看完整回答
反对 回复 2022-07-27
?
函数式编程

TA贡献1807条经验 获得超9个赞

在您的 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...");   

    }


}


查看完整回答
反对 回复 2022-07-27
  • 2 回答
  • 0 关注
  • 111 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号