Java 根据多列搜索JTable中的重复条目
我对java还是很陌生,刚刚学会使用JTables。在JTable中检查重复项时,我使用此方法仅检查关键字的一列:Java 根据多列搜索JTable中的重复条目,java,jtable,multiple-columns,Java,Jtable,Multiple Columns,我对java还是很陌生,刚刚学会使用JTables。在JTable中检查重复项时,我使用此方法仅检查关键字的一列: private boolean duplicateEntry(String entry, JTable table, int column) { System.out.print("Duplicate check for "+entry+"..."); for (int i = 0; i < table.getRowCount(); i++)
private boolean duplicateEntry(String entry, JTable table, int column)
{
System.out.print("Duplicate check for "+entry+"...");
for (int i = 0; i < table.getRowCount(); i++)
{
String found = table.getValueAt(i, column).toString();
if (found.equals(entry))
{
System.out.println(" already in db!");
return true;
}
}
System.out.println("no entry found!");
return false;
}
私有布尔重复项(字符串项、JTable表、int列)
{
系统输出打印(“重复检查“+输入+”);
对于(int i=0;i
我现在正试图让它用于更复杂的重复检查:我想检查找到的行在每一列中是否相同。为了更清楚,该表如下所示:
|名|姓|国籍|州|
如果这是我的现有条目: |约翰|史密斯|德语|德克萨斯| 如果新行的所有列的值与现有列的值相同,我希望重复检查仅返回true
因此,如果要添加| John | Smith |波兰语| Texas |->检查应返回false
因此,如果要添加| John | Smith | German | Texas |->复选框,则应返回true
我使用以下代码实现了它,但它感觉很草率和低效: hCol是表列的索引
priavte boolean duplicateEntryComplex(JTable table, String vMatch, int vCol, ArrayList<String> hMatch, int[] hCol)
{
//search for matching rows (vertical)
System.out.print("Duplicate check for "+vMatch+"...");
for (int i = 0; i < table.getRowCount(); i++)
{
String found = table.getValueAt(i, vCol).toString();
if (found.contains(vMatch))
{
// search inside found row (horizontal)
int cols = hCol.length;
ArrayList<Boolean> check = new ArrayList<Boolean>();
for (int r = 0; r < cols; r++)
{
boolean match = false;
String searchFor2 = hMatch.get(r);
String found2 = table.getValueAt(i, hCol[r]).toString();
if (found2.contains(searchFor2))
{
match = true;
}
// add result for current column to ArrayList
check.add(match);
}
for (int x= 0; x < check.size(); x++)
{
if (check.get(x) == false)
{
break;
}
if (x == check.size()-1) // if all field were identical
{
System.out.println(" already in db!");
return true;
}
}
}
}
System.out.println(" no duplicates found!");
return false;
}
priavte boolean duplicateEntryComplex(JTable table,String vMatch,int vCol,ArrayList hMatch,int[]hCol)
{
//搜索匹配行(垂直)
系统输出打印(“重复检查“+vMatch+”);
对于(int i=0;i
所以我的问题是,是否有更正确、更有效的方法来做到这一点。我和坐在我旁边的朋友的名字、姓氏、国籍和国家都是一样的。@vels4j我编辑了我的示例以使其更清楚。@pogrob您应该尝试创建一个自定义表格模型,并在其中进行重复检查。因此,您可以允许或不允许重复的行进入表中。这个问题可以解决:我通过使用Java8谓词找到了一个智能解决方案。