有人可以向我解释为什么明确需要为ForEachLoop实例分配泛型类型?
为什么编译器抱怨:类型不匹配:无法从元素类型Object转换为String?
JDK 1.5.0_09
import java.util.ArrayList;
import java.util.Collection;
public class ForEachLoop<T> {
public static void main(String[] args) {
// Non functional version
ForEachLoop f = new ForEachLoop();
// Functional version
//ForEachLoop<Integer> f = new ForEachLoop();
// Type mismatch: cannot convert from element type Object to String
for(String a : f.getStrings()) {
System.out.println(a);
}
}
public Collection<String> getStrings() {
Collection<String> strings = new ArrayList<String>();
strings.add("Hello");
return strings;
}
}
Run Code Online (Sandbox Code Playgroud) 我正在解决如何在不使用会话范围托管bean的情况下将值从一个页面传递到另一个页面的问题.对于大多数托管bean,我希望只有Request范围.
我创建了一个非常非常简单的计算器示例,它将来自第5阶段的请求bean(CalculatorRequestBean)上的操作产生的Result对象作为初始化值传递给下一阶段生命周期中初始化的请求bean的新实例.
事实上 - 在生产环境中,我们需要传递更复杂的数据对象,这不像下面定义的结果那样原始.
您对此解决方案的看法是什么,它考虑了两种可能性 - 我们保持相同的观点或者我们导航到新的观点.但在这两种情况下,我都可以使用视图范围的托管bean获取传递的先前值.
计算器页面:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Calculator</title>
</h:head>
<h:body>
<h:form>
<h:panelGrid columns="2">
<h:outputText value="Value to use:"/>
<h:inputText value="#{calculatorBeanRequest.valueToAdd}"/>
<h:outputText value="Navigate to new view:"/>
<h:selectBooleanCheckbox value="#{calculatorBeanRequest.navigateToNewView}"/>
<h:commandButton value="Add" action="#{calculatorBeanRequest.add}"/>
<h:commandButton value="Subtract" action="#{calculatorBeanRequest.subtract}"/>
<h:outputText value="Result:"/>
<h:outputText value="#{calculatorBeanRequest.result.value}"/>
<h:commandButton value="Calculator2" action="calculator2"/>
<h:outputText value="DUMMY" rendered="#{resultBeanView.dummy}"/>
</h:panelGrid>
</h:form>
</h:body>
Run Code Online (Sandbox Code Playgroud)
带有运算乘法和除法的Calculator2页面:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" …Run Code Online (Sandbox Code Playgroud)