gpt4 book ai didi

java - Java中使用字符串返回对象

转载 作者:行者123 更新时间:2023-12-01 18:42:24 27 4
gpt4 key购买 nike

我对此有点困惑,因为我对 Java 还很陌生。

这是我的问题:

我需要通过使用字符串将对象传递给另一个对象来返回一个对象。即,我想将一个字符串传递给函数(在本例中为 getObject ),然后将其与 ArrayList 进行比较。单位对象通过使用它们的 getCode功能。

到目前为止我所拥有的:

private Unit getUnitObject(String unit1Code) {
for (int i = 0; i < units.size(); i++) {
Unit currUnit = units.get(i);
String unitCode = currUnit.getUnitCode();

if (unit1Code == unitCode) {
Unit selectedUnit = currUnit;
return selectedUnit;
}
}
}

它给了我一个错误 - “此方法必须返回单位类型的结果”我尝试将 return 移出 for 循环,但仍然没有成功?我可以这样做吗?

最佳答案

问题是,如果您没有找到匹配项,则不会返回任何内容。试试这个:

private Unit getUnitObject(String unit1Code) {
for (int i = 0; i < units.size(); i++) {
Unit currUnit = units.get(i);
String unitCode = currUnit.getUnitCode();

if (unit1Code.equals(unitCode)) {
return currUnit;
}
}
return null;
}

请注意,我还使用 .equals() 比较 String 对象。如果没有匹配的内容,您可能希望返回比 null 更好的内容。

关于java - Java中使用字符串返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19430247/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com