java - 比较两个不同对象的不同列表中的元素

标签 java

我会发布我的代码,但只是更改名称。当我可以添加更多信息时,我会添加评论。

List<AbstractA> foo = bar.getFoo; // This returns an ArrayList<E> with two objects. Each object has an ID and Price. 

List<Name> names = null;
try{
   names = someClass.getNames(); // This returns an ArrayList<E> with 10 Name objects. Each one has an ID, name, description
}catch(Exception e){
   Log.warn(e);
}

我的主要目标是比较这两个列表。我有...

Iterator<Name> object = names.iterator();
while(object.hasNext()){
   Name j = object.next(); // assign next name
   System.out.println("j.getId(): " + j.getId()); // This provides me the Id
   System.out.println("foo.contains(j.getId()) " + foo.contains(j.getId())); // Keeps spitting out false but I want it to be true

   if(foo.contains(j.getId())){
      object.remove(); //remove name out of Names list
   }
}

我不确定这是否充分说明了我正在尝试做的事情。 该程序中有两个 bean,分别代表 foo 和 name。所以它们是不同的对象,我认为这可能是问题所在。

有什么建议吗?抱歉,如果这非常含糊...

我的主要问题是,如果我想比较这两个列表中的元素,最好的方法是什么?

最佳答案

List.contains(...)使用 equals()用于比较:

More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

equals() 不要求两个对象是同一个类,所以你可以像这样重写它:

class Name {

    // Stuff

    @Override
    bool equals(Object other) {
        if(other instanceof Name) {
            Name otherName = (Name)other;
            // Compare this and otherName, return true or false depending
            // on if they're equal
        } else if (other instanceof AbstractA) {
            AbstractA otherAbstractA = (AbstractA)other;
            // Compare this and otherAbstractA, return true or false depending
            // on if they're equal
        } else {
            return false;
        }
    }
}

您可能想为两者覆盖 equals(),以便 a.equals(b) == b.equals(a)。

如果您发现自己经常这样做,那么他们都实现的抽象类可能会有所帮助。

关于java - 比较两个不同对象的不同列表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13202598/

相关文章:

Java String.matches 给出错误的结果

java - 将一个普通的 jar 拉皮条成为一个带有用于 Artifactory 的内部 pom.xml 的 maven jar

java - 正在生成 PDF 报告 : jFreeChart and DynamicReports

java - 性能: float 转换为整数并将结果裁剪到范围

java - 为什么这个 while 循环适用于 "and"运算符而不适用于 "or"?

java - spring datasource xml中的bean创建是否打开与数据库的连接?

java - 在 hibernate 中通过电子邮件获取实体

java - eclipse无法导入apache tika src

java - Spring MVC - 没有找到请求 URI 的映射?

java - Java中的类似Python的装饰器?