//在remove一条信息时,
ArrayList的大小已经改变(即list.size()已经改变);
在i大于等于list.size()时,循环跳出,后便的ArrayList不能再执行;
所以必须在remove的同时,执行i--,即i=i-1;
现在才能遍历所有List中的信息。也不能在用Iterator遍历时使用remove,会抛异常。
public class TrickyAL {
public static LinkedList<User> llu=new LinkedList<User>();
public static HashMap<String,User> hmu=new HashMap<String,User>();
public static ArrayList<User> ulist=new ArrayList<User>(Arrays.asList
(new User[]{
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"));
}
public static void deleteUser(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 void deleteUser(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 void deleteUser(HashMap<String,User> urlist,String auser){
int c=urlist.size();
Iterator hmi=urlist.entrySet().iterator();
String ks="";
for(String sk : urlist.keySet()){
if(auser.equals(urlist.get(sk).name)){
System.out.println(auser);
ks=sk;
break;
}
}
urlist.remove(ks);
}
public static 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);
}
public static class User{
public int id;
public String name;
public User(int id,String name){
this.id=id;
this.name=name;
}
public String toString(){
return String.valueOf(this.id)+","+this.name;
}
}
}
ArrayList的大小已经改变(即list.size()已经改变);
在i大于等于list.size()时,循环跳出,后便的ArrayList不能再执行;
所以必须在remove的同时,执行i--,即i=i-1;
现在才能遍历所有List中的信息。也不能在用Iterator遍历时使用remove,会抛异常。
public class TrickyAL {
public static void deleteUser(LinkedList<User> urlist,String auser){
public static void deleteUser(HashMap<String,User> urlist,String auser){
}
}