Reputation: 105
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;
}
Upvotes: 3
Views: 2329
Reputation: 11454
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
. This way, you can use e.g.
List<List<StringBuilder>> groups = // ...
List<String> g = // ...
maxSimilarity(g, groups);
(StringBuilder
and String
are a CharSequence
, so they can be compared).
Upvotes: 2
Reputation: 18143
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.
Upvotes: 1
Reputation: 11483
Instead of a wildcard, declare a generic value:
public <T> static int maxSimilarity(List<T> g, List<? extends List<T>> gs);
Upvotes: 3
Reputation: 3807
Try declaring your method:
public static <T>int maxSimilarity(ArrayList<T> g, ArrayList<ArrayList<T>> groups)
Hope it helps.
Upvotes: 0