开发者

Java best practices: Put/Get SubClass objects into HashMap that expects SuperClass objects

Let's say I instantiate a HashMap with SuperClass as value-type. I then add SubClass objects as values to the Map. When I retrieve those values from the Map, they are returned as objects of type SuperClass, which I explicitly cast back to Subclass:

class SuperClass {}

class SubClass1 extends SuperClass { int one;}

class SubClass2 extends SuperClass { int two;}

class DoSomething {

   DoSomething() {
      Map<String, SuperClass> map = new HashMap<String, SuperClass>();

      map.put("1", new SubClass1());
      map.put("2", new SubClass2());

      SubClass1 one = (SubClass1) map.get("1");
   }
}

I need to know that the returned object is of the specific SubClass because I want to access methods that only exist in the SubClass. If the returned type can be any number of different SubClasses, is the use of instanceof considered best pr开发者_Python百科actice in determining the type and the casting?

SuperClass s = map.get("1");
if (s instanceof SubClass1) {
  (SubClass1)s.one = 1;
}

Thanks


There are a number of ways about this depending upon the particular situation:

  • Add an abstract method to the superclass for performing the relevant operation.
  • Use an adapter as the type of the map values. When adding the entries, use a specialisation of the adapter to match the subtype.
  • Separate maps. Particularly good if they shouldn't have been in the same map in the first place.


The best practice should be putting each SubClass type inside a different Map.

Using instanceof before performing a cast, if you really need to do that cast, it's a good idea because this way you will prevent a ClassCastException.

Pay attention that if your code has a lot of instanceof directives then you could have a bad design.

If you want to put them in the same Map then you need to think about your design:

have your DoSomething class to be aware of the differents SubClass types to perform specific operation?I see 3 possibilities:

  1. Yes, DoSomething must be aware of all your SubClass types. Then don't worry, perform your check with instanceof and cast the object retrieved from the map or, better, store them into different Maps.
  2. No, DoSomething doesn't need to be aware of the different SubClass because can use them throw the common interface SuperClass . That's good design.
  3. You don't want DoSomething to be aware of different SubClass types, but in certain situation you feel the needs to use some subclass specific methods: refactor your code, you have a wrong design.


Yes, you should definitely use instanceof to be typesafe. Otherwise, how would you know whether or not the object you pulled out is in fact the correct subclass?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜