Search code examples
javagenericsexceptionstreamsax

Adding Subtype to generic List


I am trying to add exception to a Map containing string as key and List of exceptions as values..as shown below. What I am trying to achieve is to create a generic method that can accept a Map with key as String and a list that can contain any type of exception ,if the key is of the same type add the exception to that particular List.

public static void addToMap(Map<String,List<? extends Exception>> exceptionMap,String nodeKey ,Exception exception){
exceptionMap.computeIfAbsent(nodeKey ,K->new LinkedList<Exception>).add(exception);

Note: I can add the exceptions to two different util methods seperately ...but i want it to be more generic a single util method as shown above...

I am unable to add these two different excpetions to generic util method,i dont know where i am going wrong...Any Help is Kinldly appreciated


Solution

  • You should not use wildcards here. Use wildcards only when you don't care about the exact type. But here, you do care about the exact type of list of exceptions. Namely, these two ??? must be compatible with each other:

    void addToExceptionMap(Map<String, List<???>> exceptionMap, String errorLevel, ??? exception)
    

    The last parameter can't be just any Exception, and the type of list can't just be any Exception. You can't add a NullPointerException to a list of IndexOutOfRangeExceptions, can you? These two types are related.

    You should use a generic here:

    public static <T extends Exception> void addToExceptionMap(Map<String, List<T>> exceptionMap, String errorLevel, T exception){
        exceptionMap.computeIfAbsent(errorLevel,K->new LinkedList<T>()).add(exception);
    }