----------------------
<a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ----------------------
传统集合存在的问题:
1、多线程操作时的同步问题
2、传统集合在迭代过程中不能对集合进行增删操作,利用java5的线程并发库可以解决上述问题。
示例代码:
Person类
public class Person {
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
TraditionCollectionTest类
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
public class TraditionCollectionTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Person> list = new ArrayList<Person>();
list.add(new Person("zhangsan", 13));
list.add(new Person("lisi", 15));
list.add(new Person("zhaoliu", 12));
Iterator it = list.iterator();
while (it.hasNext()) {
Person person = (Person) it.next();
if (person.getName() == "zhaoliu") {
list.remove(person);
} else {
System.out.println(person.toString());
}
}
}
}
输出结果:
现在我们修改:
让他等于李四的时候删除
输出结果:
再次修改代码:
让他等于张三的时候删除:
根据上面三次的运行结果 ,分析代码:
(为什么会出现上述情况)
查看源代码:
在ArrayList类中,有这个方法,而ArrayListIterator是其内部类。
@Override public Iterator<E> iterator() {
return new ArrayListIterator();
在ArrayList内部有一个内部类(ArrayListIterator),这个内部类维持了一个变量
private int expectedModCount = modCount;
在这个内部类的next方法中:
if (ourList.modCount != expectedModCount) {
throw new ConcurrentModificationException();
}
而modCount的值会在增加,删除时都会++。
就是说在我们程序中 调用list.iterator()时,会创建ArrayListIterator,由于之前我们add了三次,所以expectedModCount会赋值为3,当我们remove时,modCount会变为4,再执行next方法时就会抛异常。
---------------------- <a href="http://www.itheima.com"target="blank">ASP.Net+Unity开发</a>、<a href="http://www.itheima.com"target="blank">.Net培训</a>、期待与您交流! ---------------------