java - 在 Java 中有效地循环遍历具有多个变量类型的对象数组
问题描述
我正在用 Java 编写一个简单的脚本,它正在调用另一个包含我所有信息的类。
我将我的信息保存在 Object[] Arrays 中的被调用类中,并且我计划调用脚本来获取该数组。
现在函数看起来像这样。
public void tradeShop() {
/*
*Variables must be initialized in order to call shopTrader
*The values are just non-null placeholders and they are
*replaced with the same values in the tradeValues Object array.
*/
String targetName = "NPC Name";
String itemName = "Item Name";
int itemQuantity = 1;
int minCoins = 1;
int minBuy = 1;
boolean stackable = false;
Object[] tradeValues = shop.defaultValues;
for (int i = 0; i < tradeValues.length; i++) {
if(String.class.isInstance(tradeValues[i])) {//String check
if(i==0) { //0 is NPC Name
targetName = (String) tradeValues[i];
} else if (i==1) { //1 is Item Name
itemName = (String) tradeValues[i];
}
} else if (Integer.class.isInstance(tradeValues[i])) { //Int check
if(i==2) { //2 is Item Quantity
itemQuantity = (Integer) tradeValues[i];
} else if (i==3) { //3 is Minimum coins
minCoins = (Integer) tradeValues[i];
} else if (i==4) { //4 is the Minimum Buy limit
minBuy = (Integer) tradeValues[i];
}
} else if (Boolean.class.isInstance(tradeValues[i])) { //Bool check
stackable = (Boolean) tradeValues[i]; //5 is the item Stackable
} else {
//TODO: Implement exception
}
}
//Calls ShopTrader() method shopTrader
ShopTrader trade = new ShopTrader();
trade.shopTrader(targetName, itemName, itemQuantity, minCoins, minBuy, worldHop, stackable);
}
我觉得像这样使用 for 循环不是我循环这些对象的正确方法,我不应该检查每个变量的 i== 。
它还阻碍了我向 shopTrader 方法添加重载,因为我必须为每个重载编写一个全新的 for 循环。
有没有人有一个更优雅的解决方案来从这个数组中获取变量?
解决方案
我认为与其将所有信息存储在 Object[] 中,不如创建一个新类来充当数据结构,即
public class TradeValue {
String targetName;
int itemQuantity;
// etc.
String getTargetName() {
return targetName;
}
String getItemQuantity() {
return itemQuantity;
}
// etc
}
You can then just access the information directly
TradeValue defaultValues = shop.defaultValues;
String targetName = defaultValues.getTargetName();
int itemQuantity = defaultValues. getItemQuantity();
...
推荐阅读
- ruby - 设置环境变量而不在字符串和整数之间进行转换
- python - 变量没有在我的函数内部声明?
- libtorch - Torch C++ (libtorch) 中是否提供概率分布?
- augmented-reality - 深度 API 支持的设备
- javascript - 无法读取未定义的属性“startsWith”
- go - 从 docker-compose 编译 WASM 文件
- pandas - Pandas 在组中的列中的两个值之间计数
- javascript - 如何使输入密码至少需要一个特殊字符(包括括号)
- visual-studio-2019 - 在 Visual Studio 2019 中是否可以进行多插入符号复制和粘贴?
- java - 如何在不使用任何布局的情况下使文本居中?