Search code examples
javalistloopsinstanceofforge

creating a list of class objects to compare them with another class object


First of all, sorry, this question might be answered already, but my searches didn't really tell me anything and i don't really know what I am searching for anyway.

Basically, I need to create a List of class objects (only store the class / don't store initialized objects - don't really know how to explain)and compare them to another class object (ala instanceof). But I have no idea how to do this.

An Example would be:

I want to do this:

if(something1 instanceof something2)

with a List of "something1's", to be able to iterate through it like this:

for(int i= 0 ; i <= list.size; i++) 
{
  if (list.get(i) instanceof something2)
    doSomething();
}

so I basically need to know how/what I have to store in the actual list to be able to do something like that.

Is this possible?

I hope this is somewhat understandable.


Solution

  • You can compare classes using equals() method, this method will check if the class is exactly the same.

    So you first put classes in a list (assuming you have classes Foo and Bar and a list is List<Class>):

    list.add(Foo.class);
    

    And then you iterate over it and do comparison like this:

    if (list.get(i).equals(Bar.class))
        doSomething();