[英]Is there a better way to swap/update an ArrayList which is inside a Map for Java?
我的超類有一個HashMap
“ M”,其值是ArrayList,並且基於矩陣,鍵的范圍是0-N。 我在子類中創建了一個名為swap()的方法,該方法采用特定行“ x”(Map的鍵)的ArrayList並將其與另一行“ y”交換。 以下大致是我的swap()方法的樣子:
public void swap(int currentRow, int hRow ) {
ArrayList <Double> temp = new ArrayList<Double>(super.M.get(hRow));
M.put(hRow, super.M.get(currentRow));\\from super
M.put(currentRow, temp);\\ from super
}
這絕對是我想要的工作,但我想知道是否有更有效的方法? 尤其是您可以不創建數組“ temp”即通過僅使用Java Map函數來執行相同的操作嗎?
編輯1:我知道有一種方法可以執行上述操作而無需創建新的ArrayList,但是如果我想用一個像2這樣的常量乘以ArrayList中的值,然后在映射后更新該特定ArrayList,該怎么辦?是否仍可以在不創建臨時數組的情況下進行操作?
如果您不想創建額外的ArrayList temp
,則不要這樣做:
public void swap(int currentRow, int hRow ) {
ArrayList<Double> temp = super.M.get(hRow);
super.M.put(hRow, super.M.get(currentRow));
super.M.put(currentRow, temp);
}
沒有理由創建一個新的ArrayList
,您可以執行以下操作:
ArrayList<Double> temp = super.M.get(hRow);
super.M.put(hRow, super.M.get(currentRow));
super.M.put(currentRow, temp);
或者,鑒於put
返回了舊值,您甚至可以編寫:
ArrayList<Double> temp = super.M.put(hRow, super.M.get(currentRow));
super.M.put(currentRow, temp);
甚至:
super.M.put(currentRow, super.M.put(hRow, super.M.get(currentRow)));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.