I Know I can use Generics while defining the ArrayList to do that. But here the case is different.
I have a ArrayList, which when defined accepts any type of Objects. Once the user inserts the first Object, I need to use Class Reference to Find the Class of that Object and then have to ensure that only Objects of that Class are inserted in the ArrayList.
Example:
ArrayList arrayList = new ArrayList();
Now lets say the User enters an object b, of Class B in the arrayList, then from now onwards, I must only allow objects of type B to be added to the arrayList.
I know that I can find the class of the Object inserted using:
arrayList.get(0).getClass();
But what after it? How will I use the Class type I just found?
Since this is an interview question I won’t give you a complete answer, but you might want to take a look at the
Class.isAssignableFrommethod.