Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generics method signature

Tags:

java

generics

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);
}
like image 882
pstanton Avatar asked Feb 21 '23 03:02

pstanton


1 Answers

This part

<T><?extends BaseClass>

needs to be

<T extends BaseClass>

See also:

  • Generics tutorial
like image 133
BalusC Avatar answered Mar 08 '23 09:03

BalusC