java - Is it possible to change the counter variable inside a for loop? -


i trying sort linkedlist in java. need go through mylist front. elements in list objects class customelement. if match pattern want put them front.

my problem if detect element in list index 5 example matches pattern , move index 0, previous element index 4 has index 5 now, right? why want loop check element index 5 again: i++. that's causing infinite loop, whreas method's working fine without i++, not way want it, because it's skipping element index 4 (now 5).

is gernerally possible raise variable i inside loop? , if yes, doing wrong.

    (int = mylist.size() - 1; >= 0; i--) {          if (mylist.get(i) matches pattern) {               customelement helper = mylist.get(i);                             mylist.remove(i);             mylist.add(0, helper);             i++;         }     } 

it is, in case using get(i) linked list give quadratic performance.

if don't mind "matching" items being reversed in order you'd better creating new list:

final linkedlist<customelement> newlist = new linkedlist<> ();  (final customelement e: mylist) {   if (e matches pattern) { newlist.addfirst (e); }   else { newlist.addlast (e); } }  mylist = newlist; 

then problems index variables disappear...

(you achieve linear performance whilst modifying existing list, it's little more complicated.)


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -