Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Hello. Consider the following cl

Status
Not open for further replies.

rebShaul

Programmer
Jun 22, 2003
15
IL
Hello.

Consider the following classes: Obstacle, Collector.
Consider an ArrayList which contains objects of both classes.

My question is how can I determine a specific entry in the array which class it is (Obstacle or Collector)?

Thanks alot,
Shaul.
 
Not a good design. Create a typesafe collection of each rather than putting both types in the same collection.

"But, that's just my opinion... I could be wrong."

-pete
 
Oh... and chiph has a FAQ on the subject: faq732-3363

Thanks chiph [2thumbsup]

-pete
 
rebShaul -

While you *could* have objects of two different types in an arraylist (since it contains objects of type Object, it will let you do this), it's a bad idea....UNLESS one of the classes inherits from the other. In which case you would do something like this:
Code:
Object TempObject = MyArrayList[i];
if (TempObject.GetType.Name == "Obstacle") {
  Obstacle MyObstacle = (Obstacle)TempObject;
  // Do obstacle things with MyObstacle
}
if (TempObject.GetType.Name == "Collector") {
  Collector MyCollector = (Collector)TempObject;
  // Do collector things with MyObstacle
}
But, like Pete says, using a strongly-typed collection is the better way to go, as it becomes obvious what the collection contains, and protects you from your own typing errors by letting the compiler flag them.

Chip H.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top