The general list of Java lists

I am trying to make a generic function in Java to find out the maximum similarity between an ArrayList and a list from ArrayList from ArrayLists.

public static int maxSimilarity(ArrayList<?> g, 
        ArrayList<ArrayList<?>> groups){

    int maxSim = 0;
    for(ArrayList<?> g2:groups){
        int sim = similarity(g, (ArrayList<?>) g2);
        if(sim > maxSim)
            maxSim = sim;
    }
    return maxSim;
}

However, when I try to call it in my main function, it shows an incompatible error

ArrayList<ArrayList<Points>> cannot be converted to ArrayList<ArrayList<?>>

I do not understand, I know that all objects can be represented? sign. Also, it works in my similarity function, between two ArrayLists:

public static int similarity(ArrayList<?> g1, ArrayList<?> g2){
    int total = 0;
    for(Object o1:g1){
        for(Object o2:g2){
            if(o1.equals(o2))
                total++;
        }
    }
    return total;
}
+3
source share
4 answers

Instead of a wildcard, declare a common value:

public <T> static int maxSimilarity(List<T> g, List<? extends List<T>> gs);
+3
source

Change your method signature to:

public static int maxSimilarity(ArrayList<?> g, ArrayList<? extends ArrayList<?>> groups)

In general, they prefer to use interface types instead of real implementations (more flexible, less code):

public static int maxSimilarity(List<?> g, List<? extends List<?>> groups)

[edit] , -, :

public static <T> int maxSimilarity(List<? extends T> g, List<? extends List<? extends T>> groups)

, ? extends T. , , ,

List<List<StringBuilder>> groups = // ...
List<String> g = // ...
maxSimilarity(g, groups);

(StringBuilder String CharSequence, ).

+2

If you want to compare lists of similar objects, you must enter a method type parameter

public static <T> int maxSimilarity(List<T> g, List<List<T>> groups) {

because it is almost useless comparing completely different objects.

+1
source

Try declaring your method:

public static <T>int maxSimilarity(ArrayList<T> g,  ArrayList<ArrayList<T>> groups)

Hope this helps.

0
source

All Articles