Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic list of lists Java

i'm trying to make a generic function in Java to find out the maximum similarity between an ArrayList and a list from an ArrayList of 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 show an incompatible error

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

I don't understand, i tought all objects can be represented by the ? 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;
}
like image 740
windravenii Avatar asked May 30 '26 20:05

windravenii


1 Answers

Instead of a wildcard, declare a generic value:

public <T> static int maxSimilarity(List<T> g, List<? extends List<T>> gs);
like image 135
Rogue Avatar answered Jun 02 '26 11:06

Rogue