Search code examples
javaclasslinked-listvariable-assignmentinstanceof

Checking if an instance of a specific class exists in a list


Okay, apologies if this is answered already. I tried looking, but I didn't find an answer.

Now, I have a linked list utility class (linked in one direction) which contains various all purpose utility methods for different things. What I'm trying to do is make a method which is capable of taking as parametre an instance of any given class, then proceeds to check if an instance of such class exists in the list, returning true if it does, and false if it doesn't. The list itself contains instances of several different classes.

The method would be used in conjunction with a list detailing the contents of a space on a game board: If the space contains an enemy, show the icon of the enemy and make the space impassable, if it contains an item, show the icon of the item and so on and so forth. The real kicker here is that the method should be able to deal with any and all classes, so I cannot use something like:

if(foo instanceof Enemy) { . . . }

Here's what I initially tried to do: //this method is inside a LinkedList class

public boolean exists(Object o)
{
    int i = 0;
    boolean output = false;
    //koko() returns the size of the linked list
    while(i < koko() && !output)
    {
        //alkio(i) returns an Object type reference to the entity in index i
        if(alkio(i) instanceof o.getClass())
        {
            output = true;
        }
    }
    return output;
}

But it resulted in this:https://www.dropbox.com/s/5mjr45uymxotzlq/Screenshot%202016-04-06%2001.16.59.png?dl=0

Yes, this is a homework (or rather, a part of big homework) but the teacher won't answer at two AM and my google-fu is too weak.

halp plz

  • Nar

Solution

  • The dynamic way to do instanceof is to use the Class.isInstance() method:

    Determines if the specified Object is assignment-compatible with the object represented by this Class. This method is the dynamic equivalent of the Java language instanceof operator.

    So, alkio(i) instanceof o.getClass() should be written o.getClass().isInstance(alkio(i)).