【问题标题】:Verify if an object exist in a List验证列表中是否存在对象
【发布时间】:2014-12-15 18:01:52
【问题描述】:

我需要的是:验证一个对象是否存在于一个比较一些属性的列表中。

我在使用 Collections 和 Comparator 时遇到了麻烦。我正在尝试使用此二分搜索进行验证:

Collections.binarySearch(listFuncionarioObs2, formFuncionarioObsIns, formFuncionarioObsIns.objectComparator);//Binary search of an object in a List of this Object.

有了这个比较器:

public int compare(FuncionarioObs func, FuncionarioObs funcToCompare) {

    int testCodigo = -1;

    if(null != func2.getCodigo()){
        testCodigo = func.getCodigo().compareTo(funcToCompare.getCodigo());
    }

    int testData = func.getData().compareTo(funcToCompare.getData());
    int testEvento = func.getEvento().compareTo(funcToCompare.getEvento());
    int testAndamento = func.getAndamento().compareTo(funcToCompare.getAndamento());

    if(testCodigo == 0 && testData == 0 && testEvento == 0 && testAndamento == 0){
        return 0;
    }else if(testData == 0 && testEvento == 0 && testAndamento == 0) {
        return 0;
    }

    return -1;

}

但是我有点迷茫,这不起作用,我不知道最好的方法。有人可以帮我开灯吗?

最好的问候,

已编辑。

我正在使用此代码在二分搜索之前对列表进行排序:

List<FuncionarioObs> listFuncionarioObsBD = funcionarioObsDAO.getFuncionarioObsById(sigla);
Collections.sort(listFuncionarioObsBD);

排序的比较器是:

@Override
public int compareTo(FuncionarioObs func) {

        if(this.getCodigo() > func.getCodigo()){
            return 1;
        }else if(this.getCodigo() == func.getCodigo() ) {
            return 0;
        }else{
            return -1;
        }

}

【问题讨论】:

  • 您的列表实际上是按照比较器中定义的顺序排序的吗?
  • 您确定要在方法结束时返回-1,还是真的要返回testCodigo?另外:为什么你有if/else if 逻辑——这两个分支是多余的。

标签: java collections comparator


【解决方案1】:

比较

您的比较无法正常工作。现在它只是比较对象的引用。您必须更改它以比较对象值:

@Override public int compareTo(Account aThat) {
final int BEFORE = -1;
final int EQUAL = 0;
final int AFTER = 1;

//this optimization is usually worthwhile, and can
//always be added
if (this == aThat) return EQUAL;

//primitive numbers follow this form
if (this.fAccountNumber < aThat.fAccountNumber) return BEFORE;
if (this.fAccountNumber > aThat.fAccountNumber) return AFTER;

//booleans follow this form
if (!this.fIsNewAccount && aThat.fIsNewAccount) return BEFORE;
if (this.fIsNewAccount && !aThat.fIsNewAccount) return AFTER;

.
.
.
//all comparisons have yielded equality
//verify that compareTo is consistent with equals (optional)
assert this.equals(aThat) : "compareTo inconsistent with equals.";

return EQUAL;
}

来自here

寻找对象

现在是下一部分。
CrtlAltDelete 暗示它取决于您的列表是否已排序。
如果它按升序排序:遍历对象,直到找到 compareTo 返回零(== 成功)或一(== 失败)的对象。

对于未排序的列表,您必须遍历所有对象以搜索返回零的对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-11
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多