简体   繁体   中英

Is there a better way to swap/update an ArrayList which is inside a Map for Java?

My Superclass has a HashMap "M" whose values are an ArrayList and keys range from 0 - N based on a matrix. I have created a method called swap() in a subclass which takes the ArrayList of a specific row "x" (Map's Key) and swaps it with another row "y". Below is roughly how my swap() method is:

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
}

This definitely does the job I want but I was wondering if there is a more efficient way? Especially can you do the same without creating the Array "temp" ie by just using java Map functions?

Edit 1: I understand there is a way to do the above without creating a new ArrayList, but what if let's say I want to the multiply values in an ArrayList with a constant like 2 and update that particular ArrayList on the map after doing so, can I still do it without creating a temporary Array?

If you don't want to create an extra ArrayList temp , then don't do it:

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);
}

There's no reason to create a new ArrayList , you can do:

ArrayList<Double> temp = super.M.get(hRow);
super.M.put(hRow, super.M.get(currentRow));
super.M.put(currentRow, temp);

Or, given that put returns the old value, you can even write:

ArrayList<Double> temp = super.M.put(hRow, super.M.get(currentRow));    
super.M.put(currentRow, temp);

or even:

super.M.put(currentRow, super.M.put(hRow, super.M.get(currentRow)));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM