4

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

I has hoping to be able to use the same logic for 'saving' an item to the map for both cases, using Generics.

assume getId is a method of BaseClass.

I need to force

  1. the item to be a subclass of BaseClass
  2. the map value to be the same type as the item

How can I do this? here is a failed attempt which kind of 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);
}
pstanton
  • 35,033
  • 24
  • 126
  • 168
  • 4
    You're close. Replace `>` by a space. I'm however unsure how the question title is related to this. This is very confusing. – BalusC Mar 17 '12 at 04:25
  • @BalusC thanks, post your comment as an answer for the tick! – pstanton Mar 17 '12 at 05:30
  • *the map value to be the same type as the item*. Your code will enforce this as long as you mean that they have to be assignable to the same base type. If however `BaseClass` was `Number` and `item` was an `Integer`, you would not be able to enforce that `map` is a `Map` since it could always be a `Map` (in which case T is `Number`). In fact, "[PECS](http://stackoverflow.com/questions/2723397/java-generics-what-is-pecs)" suggests that `map` should be a `Map` since it shouldn't matter what exact type it is as long as you only need to add to it. – Mark Peters Mar 17 '12 at 05:35

1 Answers1

8

This part

<T><?extends BaseClass>

needs to be

<T extends BaseClass>

See also:

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555