根据多列搜索JTable中的重复条目

时间:2014-07-09 13:06:29

标签: 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++)
    {
        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;
}

我现在正试图让它更复杂的重复检查:我想检查找到的行是否在每列中都相同。为了使其更清晰,表格如下所示:

|名字|姓氏|国籍|州|


如果这是我现有的条目:

|约翰|史密斯|德国人|德克萨斯州|

如果新行的所有列都与现有列的值相同,我希望我的重复检查仅返回true。


所以如果想添加|约翰|史密斯| 波兰语 |德克萨斯州 - &GT; check应返回 false


所以如果想添加|约翰|史密斯|德国人|德克萨斯州 - &GT; check应返回 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;
}

所以我的问题是,如果有更正确和有效的方法来做到这一点。

0 个答案:

没有答案