以下两个代码示例代表相同的逻辑。检查字符串是否为空,并根据该检查进行分支。第一个示例可以安全编译。第二个产生与 Java 泛型相关的类型不匹配错误。我的问题似乎很简单,但它让我难以理解。为什么编译器会以不同的方式处理这两个语句?我怎样才能更好地理解这里发生了什么?
/* compiles cleanly */
protected Collection<String> getUserRoles(Object context,
Set<String> mappableRoles) {
String cookieValue = extractCookieValue(context);
if (cookieValue != null) {
return securityService.getRolesForUser(cookieValue);
} else {
return Collections.emptySet();
}
}
/* produces a compiler error */
protected Collection<String> getUserRoles(Object context,
Set<String> mappableRoles) {
String cookieValue = extractCookieValue(context);
return cookieValue == null ? Collections.emptySet()
: securityService.getRolesForUser(cookieValue);
}
来自 Eclipse 的编译器错误。
Type mismatch: cannot convert from Set<capture#1-of ? extends Object> to Collection<String>
根据要求,这是 SecurityService 接口的相关部分。
public interface SecurityService {
public Set<String> getRolesForUser(String userId);
}