【发布时间】:2019-04-20 11:46:18
【问题描述】:
我有一个包含三列的 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();
}
此代码用于过滤出数组,但我要做的是仅在 ArrayLists 之一不包含 s 字符串的情况下过滤 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 中得到一个异常。 有没有一种方法可以仅基于其中一个从两个数组中删除?
【问题讨论】:
-
在循环中也添加
itp.next()。 -
您不能迭代和删除元素。它不同步。但是您可以从列表开始删除 while 循环
-
如果我是你,我会采用 OOP 方法,而不是使用三个并行的
List,而是构造一个对象来保存信息并拥有一个列表 -
@GBlodgett 我之所以这样是因为数据是从 sql 数据库中获取的,而且我真的不知道有其他方法可以做到这一点,哈哈
-
@Dred 对不起,我不太明白你的意思
标签: java exception arraylist jtable illegalstateexception