我想将List<String>
强制转换为数组Integer[]
。我做了这个功能:
public static Integer[] castToArrayInteger(List<String> cadenas) {
Integer[] enteros = new Integer[cadenas.size()];
for(int iteracion = 0; iteracion < cadenas.size(); iteracion++) {
enteros[iteracion] = Integer.valueOf(cadenas.get(iteracion));
}
return enteros;
}
然后我进行了测试:
@Test
public void castToArrayInteger() {
List<String> cadenas = new ArrayList<>();
Integer[] enteros = new Integer[3];
int i = 0;
while(i < 3) {
cadenas.add(String.valueOf(i));
enteros[i] = i;
i++;
}
Assert.assertArrayEquals(enteros, ArregloUtils.castToArrayInteger(cadenas)) ;
}
它就像一种魅力。但是当我在Web应用程序中使用该功能时,它将失败。
调试工具标记该行:
Integer.valueOf(cadenas.get(iteracion));
错误是
Integer is not compatible with the declared Type String.
这是我实现函数getRubros的行:
List<CatalogoDto> rubros = this.catalogoService.buscar(
ArregloUtils.castToArrayInteger(this.getProductor().getRubrosId()));
方法getRubrosId()
获取List<String>
中的数据
我想知道为什么会有这个问题。
环境:
Java 1.8
Wildfly 16
红帽CodeReadyStudio。
我希望此输入:
List<String> data = new ArrayList<String>();
data.add("1");
data.add("2");
data.add("3");
Integer output = [1,2,3];
答案 0 :(得分:0)
只需要弄清楚使用String
(例如在测试中)将有效 int
项转换为Integer.valueOf
项的部分是不实际的问题。您尝试将{strong>不能转换为字符串的String
条目转换为字符串,如错误消息所示:
整数与声明的类型字符串不兼容。
您可以通过运行以下代码来确认问题不在转换过程中,而是要进行什么转换:
List<String> sData = new java.util.ArrayList<String>();
sData.add("1"); sData.add("2"); sData.add("3");
Integer[] iData = new Integer[sData.size()];
for (int i = 0; i < sData.size(); i++) {
iData[i] = Integer.valueOf(sData.get(i));
System.out.println(iData[i]);
}
我建议使用一些调试技术(例如断点或简单的日志记录)检查运行时正在转换的条目。这应该可以解决您的问题。