Generalization Method Signature

I have 2 different maps of different types, both of which are subclasses of BaseClass .

I was hoping to use the same logic to “save” an element on the map for both cases using Generics.

Suppose getId is a BaseClass method.

I need to make

  • item must be a subclass of BaseClass
  • map must be of the same type as item

How can i do this? here is a failed attempt that describes what I need to do:

 private <T><?extends BaseClass> void save(T item, Map<Long, T> map) { if (item.getId() == null) { long max = -1; for (Long key : map.keySet()) max = Math.max(max, key); item.setId(max + 1); } map.put(item.getId(), item); } 
+4
source share
1 answer

This part

 <T><?extends BaseClass> 

should be

 <T extends BaseClass> 

See also:

+8
source

Source: https://habr.com/ru/post/1401946/


All Articles