转自:http://blog.sina.com.cn/s/blog_4914a33b0100xtyj.html
//在remove一条信息时, ArrayList的大小已经改变(即list.size()已经改变); 在i大于等于list.size()时,循环跳出,后便的ArrayList不能再执行; 所以必须在remove的同时,执行i--,即i=i-1; 现在才能遍历所有List中的信息。也不能在用Iterator遍历时使用remove,会抛异常。 (java.util.ConcurrentModificationException; at java.util.ArrayList$ArrayListIterator.next)
public class TrickyAL {
publicstatic LinkedList<User> llu=newLinkedList<User>();
publicstatic HashMap<String,User> hmu=newHashMap<String,User>();
publicstatic ArrayList<User> ulist=newArrayList<User>(Arrays.asList
(newUser[]{
new User(2,"Eric"),
new User(3,"Eric"),
new User(1,"Aaron"),
new User(4,"Eric")
}
));
static{
llu.add(new User(1,"Aaron"));
llu.add(new User(2,"Eric"));
llu.add(new User(3,"Tom"));
hmu.put("1",new User(3,"Tom"));
hmu.put("2",new User(2,"Eric"));
hmu.put("3",new User(1,"Leo"));
hmu.put("3",new User(4,"Scott"));
}
publicstatic voiddeleteUser(ArrayList<User>urlist,String auser){
Iterator itr=urlist.iterator();
int c=urlist.size();
for(int i=0;i<c;i++){
if(auser.equals(urlist.get(i).name)){
urlist.remove(i);
i--;
c--;
}
}
}
public static voiddeleteUser(LinkedList<User>urlist,String auser){
Iterator itr=urlist.iterator();
int c=urlist.size();
for(int i=0;i<c;i++){
if(auser.equals(urlist.get(i).name)){
urlist.remove(i);
i--;
c--;
}
}
}
public static voiddeleteUser(HashMap<String,User>urlist,String auser){
intc=urlist.size();
Iteratorhmi=urlist.entrySet().iterator();
Stringks="";
for(Stringsk : urlist.keySet()){
if(auser.equals(urlist.get(sk).name)){
System.out.println(auser);
ks=sk;
break;
}
}
urlist.remove(ks);
}
publicstatic void main(String[] args) {
// TODO Auto-generated method stub
//ArrayList mul=(ArrayList)ulist;
System.out.println(ulist);
//deleteUser(ulist,"Eric");
//Arrays.sort(ulist.toArray());
System.out.println(ulist);
System.out.println("2->"+llu);
Collections.reverse(llu);
deleteUser(llu,"Eric");
System.out.println(llu);
System.out.println("3->"+hmu);
deleteUser(hmu,"Eric");
System.out.println(hmu);
Collections.copy(ulist,llu );
System.out.println(ulist);
System.out.println(llu);
}
publicstatic class User{
public int id;
public String name;
public User(int id,String name){
this.id=id;
this.name=name;
}
public String toString(){
returnString.valueOf(this.id)+","+this.name;
}
}
}