jeudi 11 août 2022

How to specify the generic type of a collection?

I want to define a function which can convert a kind of Set to another, like convert HashSet to LinkedHashSet. Here is the function declaration. The sp is sharedpreferences.

public Set<String> decodeStringSet(String key, @Nullable Set<String> defaultValue, Class<? extends Set> cls){
    Set<String> result = sp.getStringSet(key, defaultValue);
    if(result == null){
        return defaultValue;
    }
    else {
        String[] array = result.toArray(new String[0]);
        Set<String> a;
        try {
            a = cls.newInstance();
        } catch (IllegalAccessException | InstantiationException var7) {
            return defaultValue;
        }

        a.addAll(Arrays.asList(array));
        return a;
    }
}

However, the compiler remind me that "Unchecked assignment: '? extends java.util.Set' to 'java.util.Set<java.lang.String>'" on "a = cls.newInstance();". I don't know how to change cls to cls<java.lang.String>.





Aucun commentaire:

Enregistrer un commentaire