When objects of different class types are added to ArrayList. At runtime while retrieving the elements from ArrayList, How can I make it dynamically assign the objects of different class types into respective reference variables.
ArrayList contains [animal ,dog,foo,"Hello",Vector a......] Now I need to retrieve these elements and dynamically assign to a reference variable of respective types at runtime, like below.
Animal a = (Animal)ArrayList.get(0); Dog d = (Dog)ArrayList.get(1); . . . . ? xx = (?)ArrayList.get(?)
I am one of the moderators of the JavaRanch forums. Here on JavaRanch, we have a naming policy. We want the users of JavaRanch to use a real-sounding name as their display name.
Unfortunately, your name "kumar" does not comply to the naming policy. Your display name should consist of a real-sounding first name, space, and a second name. Not only a first name, no obviously fake nickname, no initials only for the second name.
Please read the naming policy carefully and change your display name. You can change your name by editing your profile.
Please note that we are taking the naming policy seriously. You have been warned multiple times before. So, update your display name ASAP. If you ignore this request, your account will be locked.
Have fun on JavaRanch, Jesper Young - Bartender [ January 09, 2008: Message edited by: Jesper Young ]
If you are putting heterogeneous objects into a collection, you should treat them all like their most base types. Either they should all implement an interface (Animal), inherit from one class (Dog), or you should treat them all like Object. Otherwise, what's the point.
baring that, check out:
and make a giant if-then statement,
also the java.lang.reflect package will provide runtime information, but that sounds more complex than you're looking for,
Bill Shirley - bshirley - frazerbilt.com
if (Posts < 30) you.read( JavaRanchFAQ);
posted 11 years ago
Is there any way to avoid huge chain of If-then clause ?
How do you think you could avoid a huge switch? You need to perform a different action of each object. So, you have 2 choices: (a) inspect each object then figure out what action to take (i.e. the naive way); or, (b) let each object figure out what it should do. If you're not familiar with it, check out polymorphism; it's the ideal solution in this case. [ January 11, 2008: Message edited by: Timothy Frey ]