首页 > 解决方案 > 如何在数组列表(Java)中搜索对象的元素,如果存在,则打印该对象的 .toString

问题描述

在我试图创建的这个特定程序中,我希望用户能够创建一个具有不同元素(字符串、整数、布尔值)的新对象,然后将其存储在 ArrayList 中,类似于大多数图书/图书馆项目。为此,我创建了一个名为 Game 的类,在其中创建了构造函数、setter/getter 以及 .toString 方法。在 mainmenu 类中,我还创建了一些 switch 语句,以根据用户的需要为用户提供不同的选择。在这里,我要求用户提供他们想要存储的新游戏的字段, 正如所指出的我忘了提到我已经创建了一个名为 storage 的 ArrayList

ArrayList <Game> storage = new ArrayList <Game> ();
private void gameInsert() 
    {
        String title;
        String desc;
        int date;
        String quality;
        Boolean given;  //(similar to the ones created in the game class)

        for (int index = 0; index < 1; index++) 
        {
        System.out.println("Please enter a title: ");
        title = keyboard.nextLine().toLowerCase();
        System.out.println("Please enter the genre: ");
        desc = keyboard.nextLine();
        System.out.println("Please enter the year of release: ");
        date = Integer.parseInt(keyboard.nextLine());
        System.out.println("Please enter the quality of the product");
        System.out.println("NC = new condition, MC= Mint condition, BC = Barely Used , U = Used ");
        quality = keyboard.nextLine().toUpperCase();
        System.out.println("Is the item borrwed to someone? ");
        System.out.println("Press 1 = Yes | Press 2 = No");
        if ( Integer.parseInt(keyboard.nextLine()) == 1) 
        {
            given = true;
        }
        else
            given = false;
        volume ++;
        storage.add(new Game(title, desc, date, quality, given ));
        } 

之后,我希望用户能够通过提供标题来搜索这个 arrayList 并找到具有相同标题的游戏的所有可用信息

private void gameSearch() 
    {

        System.out.println("Enter the game's title!: ");
        String search_title = keyboard.nextLine().toLowerCase();
        for (int i= 0; i <storage.size(); i++) 
        if(storage.equals(search_title)) 
        {
            System.out.println("The game was found!");
            // print the .toString for this particular object;
            // or print by using the getters of the game class.
           // example given: title: ----
           //                genre: ---- etc.
        }
        else 
        {
            System.out.println("I am sorry, game not found. Please try again.");
        } 

我知道我的 gameSearch 功能不起作用,但这是我所能得到的。

标签: javaobjectsearcharraylistelement

解决方案


我将假设这storage是赋予Game对象列表的名称。如果是这种情况,则storage.equals()无法工作,因为您希望列表中的特定对象等于 search_title,而不是整个列表。你可以通过这样做来完成你想要的:

for (Game game:storage) {
  if game.getTitle().equals(search_title) {
    System.out.println("The game was found!");
  }
}

但是,如果我是你,我根本不会使用列表。我会改用地图。创建地图而不是列表:

Map<String, Game> storage = new HashMap<>();

放入地图而不是添加到列表中:

storage.put(title, new Game(title, desc, date, quality, given ));

然后只需通过键搜索地图:

Game found = storage.get(title);

推荐阅读