public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("rose"); // 0
list.add("love"); // 1
list.add("lyre"); // 2
list = fix(list);
for (String s : list) {
System.out.println(s);
}
}
public static ArrayList<String> fix(ArrayList<String> list) {
// write your code here
int flag = 0;
for(String str : list){
for(int i = 0; i < str.length(); i++){
if(str.charAt(i) == 'r'){
for(int j = 0; j < str.length(); j++){
if(str.charAt(j) == 'l'){
flag = 1;
break;
}
}
if(flag == 1){
flag = 0;
break;
}
else{
list.remove(str);
break;
}
}
else if(str.charAt(i) == 'l'){
list.add(str);
break;
}
else {
if((i == str.length() - 1) && (str.charAt(i) != 'l') && (str.charAt(i) != 'r')){
break;
}
}
}
}
return list;
}
}
Why no output showing in this code?? I have used for each loop for traversing the list instead of for loop.
Under discussion
Comments (2)
- Popular
- New
- Old
You must be signed in to leave a comment
Khurram
22 March 2019, 14:55
your program is giving a ConcurrentModificationException. You are traversing the 'list' in the loop and also making modifications to it. This is not allowed. You need to copy the list in another collection and then use the copy to traverse and remove the required items from the list
0
Ashutosh Sharma
22 March 2019, 15:27
Well, after trying so hard for several hours, I have come up with a solution. It's getting accepted. Is this solution well enough or can we attempt this in several different ways?? Someone told me that we can use two arraylists to solve this question.
0