java如何在其他ArrayList中的条件为true时从ArrayList中删除项
我有一个包含三列的JTable,每个列都由ArrayList生成的数组填充。我正在尝试创建一个搜索系统,用户将在第一列中搜索一个值,JTable的行将被过滤掉,这样在按下按钮后,只有包含搜索框中指定字符串的行才会显示在表上。在另一个表中,这是通过使用以下循环过滤使用的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();
}
这段代码用于过滤掉数组,但我试图做的是仅基于其中一个ArrayList不包含s字符串的情况过滤3个ArrayList。 我试着这样做:
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();
}
当我运行这段代码时,我在线程“AWT-EventQueue-0”java中得到一个异常。在我写“itp.remove();”的行上的lang.IllegalStateException。 是否有一种方法可以仅基于其中一个从两个阵列中删除
# 1 楼答案
我很高兴你修复了你的异常。不管怎么说,当我提到反向迭代时,我的意思是这样的
首先,有些人喜欢支票
无论如何,您和我的方法不适合多线程处理,因为ArrayList不是并发对象,也是remove方法
# 2 楼答案
因此,我设法通过使用ArrayList中的remove方法而不是迭代器中的remove方法来修复它。我知道这不是推荐的方法,但它似乎没有带来任何负面影响,所以我会暂时保留它。 我使用的代码是:
感谢所有帮助过你的人