0

Let's assume I have the following classes:

public class AnSuperClass { ... }

and

public class AnBetterClass extends AnSuperClass { ... }

Also I have the following ArrayList:

private final ArrayList<AnSuperClass> theList;

and I put some object of type AnBetterClass and AnSuperClass in it like so:

theList.add(new AnBetterClass());
theList.add(new AnSuperClass());

If I iterate over the list: how do I know which one of the two classes I have? The following query will always return false:

boolean foundOther = false;
for(AnSuperClass asc: theList)
    if(!(asc instanceof AnSuperClass))
        foundOther = true;
return foundOther;

Help desirable

P.S. Annotation do not work either.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Doralitze
  • 172
  • 3
  • 11

1 Answers1

0

You can use getClass() method

    ArrayList<AnSuperClass> theList = new ArrayList<>();
    theList.add(new AnBetterClass());
    theList.add(new AnSuperClass());
    for(AnSuperClass asc: theList)
        System.out.println(asc.getClass());

that prints out

class pck.AnBetterClass
class pck.AnSuperClass
Luigi Cortese
  • 10,841
  • 6
  • 37
  • 48