简体   繁体   English

列表的通用列表Java

[英]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. 我正在尝试在Java中创建一个泛型函数,以找出ArrayList与ArrayLists的ArrayList中的列表之间的最大相似性。

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 但是,当我尝试在我的main函数中调用它时,它会显示一个不兼容的错误

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: 此外,它适用于两个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;
}

而不是通配符,声明一个通用值:

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

Change your method signature to: 将您的方法签名更改为:

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

And in general prefer using interface types, instead of actual implementations (more flexible, less code): 通常更喜欢使用接口类型,而不是实际的实现(更灵活,代码更少):

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

[edit] Based on the suggestion with the type variables, to make this super-generic, it should be: [编辑]根据类型变量的建议,为了使这个超级通用,它应该是:

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

Notice that ? extends T 请注意? extends T ? extends T . ? extends T This way, you can use eg 这样,您可以使用例如

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

( StringBuilder and String are a CharSequence , so they can be compared). StringBuilderStringCharSequence ,因此可以对它们进行比较)。

If you want to compare lists of similar objects, you should introduce a method type parameter 如果要比较类似对象的列表,则应引入方法类型参数

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

because it's nearly useless comparing completely different objects. 因为它比较完全不同的物体几乎无用。

Try declaring your method: 尝试声明您的方法:

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

Hope it helps. 希望能帮助到你。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM