确实,当您在迭代时尝试修改数组列表时会收到 ConcurrentModificationException 错误,是吗?但是,如果您首先删除要修改的元素,遍历列表,然后再将元素插入回来,错误如何仍然存在?我不明白逻辑是否是这样的,为什么它会引发并发修改异常。
整个程序使用观察者模式。
该程序的目的是拥有多个文本框,当您输入一个时,其他文本框会更新为相同的文本。
主题- 界面
public interface Subject {
public void attach(Observer o);
public void detach(Observer o);
public void notifyAllObservers();
}
SubjectImpl - 实现主题
import java.util.*;
public class SubjectImpl implements Subject {
private List <Observer> observers;
public SubjectImpl(){
observers = new ArrayList<Observer>();
}
@Override
public void attach(Observer o) {
observers.add(o);
}
@Override
public void detach(Observer o) {
observers.remove(o);
}
@Override
public void notifyAllObservers() {
//Iterating code
for(Observer o: observers){
o.update();
}
}
}
观察者- 界面
public interface Observer {
public void update();
}
编辑器- 实现观察者
import java.awt.*
import java.io.*;
import javax.swing.*;
public class Editor extends JFrame implements DocumentListener, Observer {
private FileContentSubject reference;
private JScrollPane textAreaScrollPane;
private JTextArea textArea;
public Editor(FileContentSubject filecontentsubject) throws IOException {
super("Editor");
initComponents();
this.reference = filecontentsubject;
textArea.getDocument().addDocumentListener(reference);
textArea.getDocument().putProperty("ownerEditor", this);
}
private void initComponents(){
textArea = new JTextArea();
//set location, size, visible and defaultcloseoperation here
getContentPane().setLayout(new BorderLayout());
getContentPane().add(textArea, BorderLayout.CENTER);
}
@Override
public void update() {
textArea.setText(reference.getState()); //Call to update each text box
}
@Override
public void changedUpdate(DocumentEvent e) {
}
@Override
public void insertUpdate(DocumentEvent e) {
}
@Override
public void removeUpdate(DocumentEvent e) {
}
}
文件内容系统- 作为观察者中的具体主题(只有一个)
import javax.swing.event.*;
import javax.swing.text.*;
public class FileContentSubject implements Subject, DocumentListener {
private String state; //Current, most recent copy of everything
public String getState() {
return this.state;
}
private SubjectImpl reference;
@Override
public void attach(Observer o) {
reference.attach(o);
}
@Override
public void detach(Observer o) {
reference.detach(o);
}
@Override
public void notifyAllObservers() {
reference.notifyAllObservers();
}
public FileContentSubject() {
reference = new SubjectImpl();
}
@Override
public void changedUpdate(DocumentEvent arg0) {
}
@Override
public void insertUpdate(DocumentEvent arg0) {
Document doc = (Document) arg0.getDocument();
try {
this.state = doc.getText(0, doc.getLength());
} catch (BadLocationException e) {
e.printStackTrace();
}
Editor e = (Editor) doc.getProperty("ownerEditor");
reference.detach(e);
notifyAllObservers();
reference.attach(e);
}
@Override
public void removeUpdate(DocumentEvent arg0) {
//same as insertUpdate(DocumentEvent arg0) ^^
}
}