0

I have 2 different Objects(with their own methods) inside a Collection :

public class Hero {
[...]
  public int getLevel(){
    return level
  }
}
public class Monster {
[...]
  public int getLevel(){
    return level
  }
}

I shuffle my Collection to randomly change the order of elements :

List<Object> fighters = Arrays.asList(hero, monster);
Collections.shuffle(fighters);

After that, I need to iterate on the Collection and call Object's methods (they got the same name for both objects).

Is it possible ? I tried with for loop, Iterator and I always receive error message : The method getLevel() is undefined for the type Object

Example of my last tries:

1

        Iterator<Object> iterator = fighters.iterator();
        while (iterator.hasNext()) {
            Object ob = iterator.next();
            System.out.println("character level :" + ob.getLevel());
        }

2

        for (Object p : fighters) {
            System.out.println("character level :" +  p.getLevel());
           ;
        }

Q: How can I iterate on a Collection and use Object methods?

Let me know if I can be more clear (i didn't find how to make a java snippet)

Community
  • 1
  • 1
Boris BELLOC
  • 196
  • 1
  • 4
  • 15
  • 1
    Why did you throw away type information on purpose? Do not collect them in a `List`. Use an interface to group their similarities and then have a list over that interface. Then you can also call the method. – Zabuzard Nov 10 '19 at 15:31
  • Technically you can check the type with `instanceof` and then **cast**. Afterwards you can call the method again. But this usually, and especially in this case, indicates poor design. I.e. why throw away the type information in the first place. – Zabuzard Nov 10 '19 at 15:32
  • 3
    Use an interface like `public interface HasLevel { int getLevel(); }`. – Zabuzard Nov 10 '19 at 15:34
  • I put them in Collection because it's the only solution I thought of to randomly choose who will be first; Object was my only common property, that why I choose it as type. Thanks for your solutions! – Boris BELLOC Nov 10 '19 at 15:40
  • 1
    Fair enough. Just introduce a common property that still has the method, thats why there are interfaces :) – Zabuzard Nov 10 '19 at 16:08

0 Answers0