Multiple classes in an (undefined) ArrayList?

In your code

  • aPlayer if of type playerClass
  • sampleList holds instances of type Object
  • sampleList.get(i); returns an instance of type `Object’

A variable of type playerClass can not reference an instance of type Object so
aPlayer = sampleList.get(i);
fails

In this code
aPlayer = (playerClass) sampleList.get(i);
the returned Object instance is cast to the type playerClass so it’s reference can be stored in a playerClass variable i.e. aPlayer hence it works. The technique is called casting

The problem with this code is, if the returned instance is not of type playerClass (or a child class of playerClass) then the statement
aPlayer = (playerClass) sampleList.get(i);
will crash at runtime.

That is why you never see lists declared like this
ArrayList sampleList = new ArrayList();
except in ancient legacy code.

4 Likes