i use this code to check the data in an arraylist and remove the similarities but i got a ConcurrentModificationException. this is the final code after solving all the problems:
public class Aaa {
static ArrayList <String> cmp = new ArrayList<String>();
static ArrayList <String> cpr = new ArrayList<String>();
public static void clarify(ArrayList<String> cmp) {
for (int i = 0; i< cmp.size(); i++){
cpr.add("null");
}
java.util.Collections.copy(cpr, cmp);
for (String s : cpr){
int j = 0;
Iterator<String> itr= cmp.iterator();
while (itr.hasNext()){
String t = itr.next();
if (s.equals(t)){
j++;
if (j > 1){
itr.remove();
}
}
}
}
for(String x : cmp){
System.out.println(x);
}
}
public static void main(String args[]){
cmp.add("hamada");
cmp.add("ramzy");
cmp.add("morsy");
cmp.add("attres");
cmp.add("hamada");
cmp.add("el nenny");
cmp.add("hamada");
cmp.add("abbas");
clarify(cmp);
}
}
You cannot modify the same array on which you are iterating.
You are iterating on cmp and trying to modify the same. This is the cause of your exception.
for (String s : cpr){
for(String t : cmp){
if (t.equals(s)){
cmp.remove(t);
}
}
}
use iterator instead
for (String s : cpr){
Iterator<String> itr= cmp.iterator();
while (itr.hasNext()){
String t = itr.next();
if (s.equals(t)){
itr.remove();
}
}
}