0

I have a method which takes a Collection<Object> where the Object can be a String or CustomClass. It then takes each element of the collection and passes it to a method with an argument of Object like so:

public void foo(Collection<Object> c) {
    for(Object o : c)
        bar(o);
}

public void bar(Object o) {
    if(o instanceof String || o instanceof CustomClass) {
        ...
    }
}

bar works fine when I pass it a String or CustomClass, but when I try to pass a NavigableSet<String> to foo I get cannot find symbol; symbol : method foo(java.util.NavigableSet<java.lang.String>).

However if I change the the argument type in foo to Collection<String> it works fine, but this means I need to make a new foo(Collection<CustomClass>) method which will involve repeating code. Is there a way around this?


Comparing two rows in SQL Server

Scenario

A very large size query returns a lot of fields from multiple joined tables. Some records seem to be duplicated. You accomplish some checks, some grouping. You focus on a couple of records for further investigation. Still, there are too much fields to check each value.

Question

Is there any built-in function that compares two records, returning TRUE if the records match, otherwise FALSE and the set of not matching fields?

4

2 回答 2

5

Collection<String>不是 的子类型Collection<Object>,因此编译器找不到任何兼容的方法。放

public <T> void foo(Collection<T> c) {
  for (T o : c) bar(o);
}
于 2012-07-17T10:00:39.223 回答
0

T<A>和之间的继承关系T<B>称为“泛型协方差”。它不是简单的,如果A从 继承B,然后T<A>从 继承T<B>,因为类型参数可能是“in”或“out”(就像 C# 所说的那样)。

参见例如http://www.ibm.com/developerworks/java/library/j-jtp01255/index.htmljava generics covariancehttp://etymon.blogspot.co.uk/2007/02/java-generics -and-covariance-and.html

Marko 的建议是解决您问题的最简单方法。

于 2012-07-17T10:04:11.087 回答