我有一个包含三列的JTable,每一列都填充有一个由ArrayList组成的数组。我正在尝试创建一个搜索系统,在该系统中,用户将在第一列中搜索值,并且JTable的行将被过滤掉,以便只有包含来自搜索框的指定String的行才会显示在按下按钮后的表格。在另一个表上,这通过过滤使用此循环的ArrayList起作用:
String s = searchBar.getText();
ArrayList<String> fn = new ArrayList<>();
fn.addAll(names); //names is the arraylist that contains all the values that will be filtered
for(Iterator<String> it = fn.iterator(); it.hasNext(); ) {
if (!it.next().contains(s)) {
it.remove();
}
这段代码可以过滤掉数组,但是我要尝试的是仅在ArrayLists之一不包含s String的情况下才过滤3个ArrayLists。 我尝试这样做:
String s = searchBar.getText();
ArrayList<String> fn = new ArrayList<>();
ArrayList<String> fp = new ArrayList<>();
fn.addAll(names); //names is the arraylist that contains all the values that will be filtered
fp.addAll(numbers)//one of the other arraylists that I want to filter
for(Iterator<String> it = fn.iterator(), itp = fp.iterator(); it.hasNext() && itp.hasNext(); ) {
if (!it.next().contains(s)) {
itp.remove();
it.remove();
}
运行此代码时,在写“ itp.remove();”的那一行上,线程“ AWT-EventQueue-0” java.lang.IllegalStateException中出现异常。 有没有一种方法可以仅基于其中一个从两个阵列中删除?
答案 0 :(得分:1)
所以我设法通过使用ArrayList中的remove方法而不是Iterator中的remove方法来修复它。我知道这不是推荐的方法,但是它似乎并没有带来任何负面影响,因此我将暂时保留它。 我使用的代码是:
int i = 0;
for (Iterator<String> it = fn.iterator(); it.hasNext(); i++) {
if (!it.next().contains(s)) {
it.remove(); //Iterator's remove
fp.remove(i);// ArrayList's remove which avoids the error
}
}
感谢所有帮助过的人
答案 1 :(得分:1)
很高兴您能解决例外情况。无论如何,当我说到反向迭代时,我的意思是这样的
首先,一些类似的支票
if(fn.size()==fp.size()){
// and after that go to delete.
for (int i=fn.size(); i>0;i--) {
if (fn.contains(s)) {
fn.remove(i);
fp.remove(i);
} }}
无论如何,您和我的方法都不适合多线程处理,因为ArrayList不是并发对象,它也是remove方法