简体   繁体   English

如何比较两个数组列表,这些数组列表包含属于同一超类但属于各种子类的对象的实例。

[英]How to compare two array lists that consist of instances of objects that belong to the same superclass, but various subclasses.

So far I came up with that. 到目前为止,我想到了这一点。

public static boolean challenge(ArrayList<Thing> required, ArrayList<Thing> owned){

    boolean result=false;

    for(int i=0; i<=required.size(); i++)
    {
        for(int j=0; j<=owned.size(); j++)
        {
            ///compare each required to all owned
            ///if (required.get(i) instanceof owned.get(j))
            {   result=true;
            }

            /// else
            {
                result=false;
                break;
            }
        }   
    }

    return result;
}

it gives me compile error in the if statement. 它给我if语句中的编译错误。 " ')' expected " “')'预期的”

I am a bit lost. 我有点迷路。 Any help would be appreciated. 任何帮助,将不胜感激。

You may want to use required.get(i).getClass() == owned.get(j).getClass() instead. 您可能要使用required.get(i).getClass() == owned.get(j).getClass()

Also consider using 'for each' eg 也可以考虑使用“ for each”,例如

for(Thing r : required) {
    for (Thing o : owned) {
      if (r.getClass() ...
        ...
    }
}

As Alex Nevidomsky said, instanceof should be used with the type on the right part. 正如Alex Nevidomsky所说, instanceof应该与右边的类型一起使用。 Should be if (required.get(i) instanceof owned.get(j).getClass()) maybe this link will be helpful also 应该是if (required.get(i) instanceof owned.get(j).getClass()) 也许这个链接也会有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM