Incidentally, is there a workaround to using the instanceof keyword here?
Yes.
First, you must abandon the orthodox methods of reasoning - they are horribly contrived. I realise this is the beginner's forum, and nobody likes anything slightly "left wing" in here, so you can contact me offline for further clarification if you choose.
An incomplete set of axioms of "software in Java":
- You can (and should) *always* avoid the use of instanceof
- You can (and should) *always* avoid a cast
In short, you can achieve these objectives with appropriate abstractions (insert lengthy explanation here).
However, you have restricted your context to "software in
Java using ArrayList". A common mistake here is to assume legitimacy of the abstraction that you are using - ArrayList (and many collection types) are flawed (they contain implicit contradictions in their objectives through formal analysis). The subjectivity of this assertion often digresses to identifying language flaws that force inappropriate abstraction *no matter what* - only that for many types, the "inappropritateness" is taken to an extreme.
Do not assume the legitimacy of ArrayList and analyse it. While there are infinite flaws ("infinite" meaning literally - not to exaggerate a real number), the particular flaw that you are observing is really quite trivial - and of course, you will be told by the marketing/JSR folk that the "contains" method of the List type must accept type Object for the remainder of that type's life for reverse compatibility. I might digress to the underlying flaw of this reasoning, but again, I am probably already exceeding the permitted dialogue in a beginner forum.
Instead, I will simply respond, "does List/ArrayList meet your requirement?" - Clearly not, since you observe a failure of abstraction (and you even acknowledge it with "how can I not use instanceof?"). The answer then is "either concede to the flawed type, or write the type yourself" - these are your only two options within the context of Java. Once you restrict yourself to ArrayList/List, you lose the latter option, in which case, the answer simply becomes "no, you cannot avoid instanceof".
As a side note, why are you extending ArrayList? Many code style checkers will bonk you on the head for that (despite only minimising the damage of the undocumented flaws that I refer to - instead of eliminating them).
I hope this helps.