亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

比較數組之間的所有元素并返回所有可能的匹配項

比較數組之間的所有元素并返回所有可能的匹配項

慕妹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 關注
  • 103 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號