Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Use different methods depending of the instance of the class

I have the following HashMap:

HashMap<Integer, Object> ItemsData = new HashMap<Integer, Object>();

In the HashMap, I have objects of various classes, such as

  • ClassOne
  • ClassTwo
  • ClassThree

Each class has its own methods, attributes etc.
How do I refer to proper method, depending on the instance of the class?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For example:

  • ItemsData.get(5).bark() -> because item 5 is instance of class 1 which has method bark
  • ItemsData.get(2).jump() -> because item 2 is instance of class 2 which has method jump
  • ItemsData.get(6).fire() -> because item 6 is instance of class 3 which has method fire

>Solution :

Generally having such an untyped map in the first place is a code smell. You didn’t explain enough of the underlying problem you’re trying to solve to give you good advice on a nicer solution; merely to point out that this solution probably is severely suboptimal.

If you insist on using it, you can use instanceof to check if a value is of a certain type, and use a cast operator to treat it as a certain type:

Map<Integer, Object> badIdea = new ....;

...

Object secondValue = badIdea.get(1);
if (secondValue instanceof Dog) {
  Dog dog = (Dog) secondValue;
  dog.bark();
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading