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?
ArrayListdirectly they'll be able to insert whatever they like won't they? Is the idea that you are supposed to write your own class that extendsArrayList, or that usesArrayListfor internal storage, where your class will enforce the first-object-stored-restricts-the-rest requirement? (If this is an "interview question" does that mean you're sitting in the interview right now hoping for a response on your smartphone?)