【发布时间】:2020-05-07 22:20:03
【问题描述】:
我正在尝试通过 indexOf 获取 ArrayList 的索引。到目前为止,我已经得到了
我的数组列表:public static ArrayList<Shop> allShops = new ArrayList();
应该得到什么索引
Scanner editShop = new Scanner(System.in);
String shopToEdit = editShop.nextLine();
int i = allShops.indexOf(shopToEdit);
System.out.println(i); //see what our index is (returns -1 because the var doesn't seem to get the right input)
EditFunc.edit(i);
这应该会改变我的数组列表
public static void edit(int index){
//change array with given input in edit
//TODO: Make it so they can choose what to edit
//with booleans if editTrueName = false and then later on make it true again
System.out.println("Enter the new shop name:");
Scanner editedShopAttribute = new Scanner(System.in);
String editedShopName = editedShopAttribute.nextLine();
System.out.println("Enter the new shop location:");
String editedShopLocation = editedShopAttribute.nextLine();
Shop EditedVar = new Shop();
EditedVar.createShop(editedShopName,editedShopLocation);
allShops.set(index, EditedVar);
}
我已经复制了调试器显示给我的值并用它替换了它们,但它似乎仍然不起作用。我是否接收了错误类型的数据?我可以尝试什么?
如果我的代码看起来有问题,我总是会努力改进它。
【问题讨论】:
-
您正在搜索
String的索引。不是Shop。 -
@azurefrog,所以我需要获取所述值的哈希码并检查它是否相等?
-
不,您需要创建一个
Shop对象并搜索它。由于这没什么意义,您应该考虑将List<Shop>更改为Map<String, Shop>,这样您就可以通过name直接查找Shop。这也会表现得更好,因为它不是顺序搜索。 -
谢谢@Andreas 我会试试看!