1

Hey guys im stuck on a problem. Say I have an interface Animal. I then have classes that implement it such as Dog, Cat, Goat. say each of these classes has an update() function that they get from the interface.

I have an arraylist of Animal,that includes all different kinds of the animal classes (dog, cat, goat). If i was given a string that says "Goat" how would i search that arraylist and choose only the Goat update() function, ignoring Dog and Cat...

0

3 Answers 3

6
for ( Animal a : animals ) {
    if ( a instanceof Goat ) {
       a.update();
    }
}

If you really only have the String "Goat" to go on you could do something like this:

if ( a.getClass().getName().endsWith("Goat") ) {
    //...

Or if the String has nothing to do with the name of the class, you could map a String to an instance of Class:

Map<String, Class<? extends Animal>> map = new HashMap...
map.put("Goat", Goat.class);

//...
if ( map.get("Goat").isInstance(a) ) {
   a.update();
}

In my opinion Google's Guava is the best choice:

 for ( Goat g : Iterables.filter(animals, Goat.class) ) {
    g.update();
 }
Sign up to request clarification or add additional context in comments.

2 Comments

yes i only have the string to go by, so the second option did the trick
@Jonathan: you might want to be careful with that, as this would also update all PrairieDogs if you passed in "Dog", for example. A better way would be to use a.getClass().getSimpleName().equals("Goat") However, in both cases you won't be matching subclasses of Goat, only objects which are exactly Goat. The third option is more stable.
1
public void goatUpdate(List<Animal> animals) {
    for (Animal animal : animals) {
        if (animal instanceof Goat) {
            animal.update();
        }
    }
}

Comments

0

I am afraid you will need to go through the list asking for the type of each object. If you have List<Animal> there is (as far as I know) no easy one-line way to get only specfied subclass of it.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.