【问题标题】:How to get the right input to get my ArrayList's index?如何获得正确的输入来获取我的 ArrayList 的索引?
【发布时间】: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 我会试试看!

标签: java oop arraylist


【解决方案1】:

我不相信您可以使用数组制作您想要的东西。其中一个 cmets 指出的原因是您正在寻找一个字符串,但该数组包含 Shop(s)。由于 Shop 不仅仅包含 ShopName,因此您将永远无法通过这种方式找到它。您应该为此目的使用“地图”:

public static Map<String, Shop> allShopsMap = new HashMap<>();

如果您将所有商店添加到此地图,那么当您获得 ShopName 作为输入时,您只需执行以下操作:

Shop shopToEdit = allShopsMap.get(inputShopName);

然后调用此对象的 set 方法来更改名称和位置。

【讨论】:

    【解决方案2】:

    你不能用Map&lt;String, Shop&gt; 来做吗?这样您就可以使用shopName 作为键。

    顺便说一句,当我看到你的新 Java 和 OOP 时,我强烈建议你阅读 Robert C. Martin 的 Clean Code,这是一本改变游戏规则的书。

    【讨论】:

      猜你喜欢
      • 2012-07-21
      • 2018-07-25
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2021-12-31
      相关资源
      最近更新 更多