Modifying an ArrayList in Java -


i want search through arraylst , delete entries same.

for example if list was: apple, orange, banana, pear, peach, orange,

then "orange" deleted (both occurances).

naively, tried:

for(string word : userlist){  for(string otherword : userlist){  ... } } 

where wrote how .remove(lastindexof(userword)) if equals word and indexes different.

this led exception after exception, , realized manipulating list while iterating through making go wrong.

so decided make copy of list

arraylist<string> copylist = userlist;  for(string word : copylist){      for(string otherword : copylist){      if(word.equalsignorecase(otherword)              && copylist.lastindexof(word)!=copylist.lastindexof(otherword)){  userlist.remove(userlist.lastindexof(word)); userlist.remove(userlist.lastindexof(otherword));     }      }     } 

so tried this, , had similar problems. notably concurrentmodificationexception. after tweaking can't get, in head should easy process, work in java. please help.

you're not making copy of list @ all. you're declaring new variable has reference same list. make copy of list, use:

arraylist<string> copylist = new arraylist<string>(userlist); 

however, i'd suggest different approach:

arraylist<string> wordstoremove = new arraylist<string>(); set<string> seenwords = new hashset<string>();  (string word : userlist) {     if (!seenwords.add(word))     {         wordstoremove.add(word);     } }  (string word : wordstoremove) {     // keep removing until doesn't exist more     while (userlist.remove(word)) {} } 

this doesn't ignore case, however. that, need bit smarter:

set<string> wordstoremove = new treeset<string>(string.case_insensitive_order); set<string> seenwords = new treeset<string>(string.case_insensitive_order);  (string word : userlist) {     if (!seenwords.add(word))     {         wordstoremove.add(word);     } }  // know words don't want, step through list again , // remove them (case-insensitively, wordstoremove case-insensitive) (iterator<string> iterator = userlist.iterator(); it.hasnext() ;) {     if (wordstoremove.contains(word))     {         iterator.remove();     } } 

Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -