1

I have a simple utility function like following:

public static <T, S> HashSet<S> convertSet(Set<T> list, IConverter<T, S> converter)
{
    HashSet<S> result = new HashSet<>();
    if (list != null)
    {
        for (T item : list)
            result.add(converter.convert(item));
    }
    return result;
}

I want that the result of this funtion is of the same type as the input data, so I tried to change the function to following:

public static <T, S, ST extends Set<T>, SS extends Set<S>> SS convertSet(ST list, IConverter<T, S> converter)
{
    // following is not working of course!
    // I can't create a new object of the generic type!
    SS result = new SS();
    if (list != null)
    {
        for (T item : list)
            result.add(converter.convert(item));
    }
    return result;
}

Is there any way to write this so that it works? In c++ we have templates and the compiler will generate all necessary functions itself, is there anything like this in java?

Or any annotation library so that I can annotate my function with all Set classes I want to support and which will generate the concrete functions for me?

I want to avoid to write a function for each Set class manually...

prom85
  • 16,896
  • 17
  • 122
  • 242
  • Simple answer: Java generics are not C++ templates. Read about things like "runtime type erasure" for example. – GhostCat Mar 01 '17 at 13:20

0 Answers0