java - Is it safe to do a Collections.swap() inside a arraylist for loop? -


i have following code:

private list<string> listofstrings = new arraylist<>(); listofstrings.add("a"); listofstrings.add("b"); listofstrings.add("c"); listofstrings.add("d");  (string temp : listofstrings) {   if (temp.equals("c")) {     collections.swap(listofstrings, 0, listofstrings.indexof(temp));   } } 

the list may not list of string list of objects defined class wrote. i'm not sure swap here, see compiled , running fine don't know if it's safe here.

does have suggestions on this? if need swap. planned use for (int = 0; < size; i++) iterate , use list.get(i) item, think it's not idea use list.get(i) on arraylist?

any appreciated!! in advance!!

if worried concurrentmodificationexception, yes, calling swap within loop safe.

the enhanced loop use iterator internally, , iterator may throw concurrentmodificationexception when detects structural modification of list not done iterator itself. although modify list, not doing structural modification: structural modification modification in size of list (or backing array) changes. merely setting value not considered structural modification. java api documentation:

(a structural modification operation adds or deletes 1 or more elements, or explicitly resizes backing array; merely setting value of element not structural modification.)

however, using index-based loop in case faster. reason indexof(temp) call needs find object obtain index, has loop through list items again. algorithm has quadratic running time. in index-based for-loop know index of element want swap, not necessary, , have linear running time.


Comments

Popular posts from this blog

javascript - How to get current YouTube IDs via iMacros? -

c# - Maintaining a program folder in program files out of date? -

emulation - Android map show my location didn't work -