I have to edit the list of String:
- Delete the value if it contains "h" letter;
- Do nothing if it contains "h" and "o"
- Add to the list duplicate of the value if it contains letter "o".
I stuck on a step of making a duplicate. What is wrong? And why occurs?
Here is the code:
public class MyClass {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<String>();
list.add("hi"); // this one have to be removed
list.add("hello"); // this one have to be left without changes
list.add("ops"); // duplicate must be added to the list
list = fix(list);
for (String s : list) {
System.out.println(s);
}
}
public static ArrayList<String> fix(ArrayList<String> list) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).contains("h") && list.get(i).contains("o")) ;
// do nothing
else if (list.get(i).contains("h"))
list.remove(i);
else if (list.get(i).contains("o")) {
// The problem is here ===>
list.add(i + 1, list.get(i));
}
}
return list;
}
}
I also tried:
String s = new String(list.get(i));
list.add(i+1, s);
list.add(i, list.get(i++));?