【问题标题】:How do I use contains to search through a custom object ArrayList for a particular string?如何使用 contains 在自定义对象 ArrayList 中搜索特定字符串?
【发布时间】:2015-10-20 17:17:59
【问题描述】:

我对编程(昨天开始......)和 Java 完全陌生,所以请原谅任何愚蠢的错误和非常糟糕的代码(我不知道如何订购/格式化)。我的任务是制作视频清单,我希望能够搜索清单以检查特定视频是否存在。

我知道我可以使用 contains 来执行此操作,但我无法让它与我的自定义对象 ArrayList(视频)一起使用,我希望它搜索所有数据(下面的每个 InventoryRow)。我已经覆盖了 equals 和 HashCode 但它仍然无法工作 - 每当我尝试运行代码时,它总是会告诉我即使视频在那里也找不到视频。 (仅供参考,我在代码的末尾包含了租金和检查功能)

我非常感谢任何帮助,因为我整天都在谷歌搜索无济于事。此外,如果这不能完成或其他方法会更好,请告诉我!谢谢。

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

class InventoryRow {
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result
            + ((availability == null) ? 0 : availability.hashCode());
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    result = prime * result
            + ((returndate == null) ? 0 : returndate.hashCode());
    result = prime * result + ((type == null) ? 0 : type.hashCode());
    return result;
}

@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    InventoryRow other = (InventoryRow) obj;
    if (availability == null) {
        if (other.availability != null)
            return false;
    } else if (!availability.equals(other.availability))
        return false;
    if (name == null) {
        if (other.name != null)
            return false;
    } else if (!name.equals(other.name))
        return false;
    if (returndate == null) {
        if (other.returndate != null)
            return false;
    } else if (!returndate.equals(other.returndate))
        return false;
    if (type == null) {
        if (other.type != null)
            return false;
    } else if (!type.equals(other.type))
        return false;
    return true;
}

private String name;
private String type;
private Character availability;
private String returndate;

public InventoryRow(String name, String type, Character availability,
        String returndate) {
    this.name = name;
    this.type = type;
    this.availability = availability;
    this.returndate = returndate;
}

public String getReturndate() {
    return returndate;
}

public void setReturndate(String returndate) {
    this.returndate = returndate;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getType() {
    return type;
}

public void setType(String type) {
    this.type = type;
}

public Character getAvailability() {
    return availability;
}

public void setAvailability(Character availability) {
    this.availability = availability;
}

public String toString() {
    return name + "   " + type + "   " + availability + "   " + returndate;
}
}

public class InventorySort {

public static void main(String[] args) {
    List<InventoryRow> videos = new ArrayList<InventoryRow>();

    videos.add(new InventoryRow("Casablanca", "Old", 'Y', "1 January 2015"));
    videos.add(new InventoryRow("Jurassic Park", "Regular", 'N',
            "1 January 2015"));
    videos.add(new InventoryRow("2012", "Regular", 'Y', "1 January 2015"));
    videos.add(new InventoryRow("Ant-Man", "New", 'Y', "1 January 2015"));

    // Another ArrayList because I can't seem to search through the first
    // one?
    /*ArrayList<String> names = new ArrayList<String>();
    names.add("Casablanca");
    names.add("Jurassic Park");
    names.add("2012");
    names.add("Ant-Man");*/

    Scanner input = new Scanner(System.in);

    // Output the prompt
    System.out.println("What do you want to do?");

    // Wait for the user to enter a line of text
    String line = input.nextLine();

    // List, rent and check functions
    // List function
    if (line.equals("l")) {
        // Sort function
        Collections.sort(videos, new Comparator<InventoryRow>() {
            public int compare(InventoryRow o1, InventoryRow o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (InventoryRow inventory : videos) {
            System.out.println(inventory);
        }
        // Rent function
    } else if (line.equals("r")) {
        System.out.println("Which video would you like to rent?");
        String line2 = input.nextLine();
        // Search through ArrayList
        if (videos.contains(line2)) {
            System.out.println("Video available to rent!");
        } else {
            System.out.println("Video unavailable to rent.");
        }
        // Check function
    } else if (line.equals("c")) {
        System.out
                .println("Which video would you like to check is in the inventory?");
        String line3 = input.nextLine();
        // Search through ArrayList
        if (videos.contains(line3)) {
            System.out.println("Video found!");
        } else {
            System.out
                    .println("Video not found. Please see the inventory below.");
            Collections.sort(videos, new Comparator<InventoryRow>() {
                public int compare(InventoryRow o1, InventoryRow o2) {
                    return o1.getName().compareTo(o2.getName());
                }
            });
            for (InventoryRow inventory : videos) {
                System.out.println(inventory);
            }
        }
        // If anything else is entered
    } else {
        System.out
                .println("The only options are to list (l), rent (r) or check (c).");
    }

}
}

【问题讨论】:

  • 您将InventoryRowString 进行比较。
  • 换句话说,苹果有多少根香蕉?

标签: java search arraylist contains inventory


【解决方案1】:

您可以使用包含。但是,对于编程的第一天,简单地遍历您的库存,将输入字符串与视频名称进行比较可能更容易理解:

    boolean foundIt = false;
    for (InventoryRow ir : videos) {
        if (line3.equals(ir.getName())) {
            foundIt = true;
            break;
        }
    }
    if (foundIt) {
        System.out.println("Video found!");

【讨论】:

  • 我将如何更改它以使其仅返回“找到视频!”如果用户输入视频的可用性设置为“Y”?其实我想我想通了,这行得通吗? if (line2.equals(ir.getName()) &amp;&amp; ir.getAvailability() == 'Y')
  • @ini 是的,应该可以。如果可用性只有两个可能的值,您可以将其类型更改为布尔值(或者,如果它也可以为空,则更改为布尔值)。这样你就不用担心字母大小写了。
  • 是的,我正在考虑将可用性更改为布尔值。这有什么好处吗?
  • @Ini 一般来说,最好使用最简单的数据类型来模拟您希望字段包含的信息。布尔值比字符简单。字符比字符串简单。我猜,视频的可用性有两个值,要么可用,要么不可用。如果您需要对其他情况进行建模,例如即将推出,那么您可能会求助于 Java 枚举。 enum Availability { AVAIL_NOW, AVAIL_SOON, NOT_AVAIL }那么你可以使用Availability作为字段类型而不是Character。
【解决方案2】:

替代@kilo 答案,您可以仅在视频类的名称上实现equals 和hashcode 方法,并按以下方式检查。

String line3 = input.nextLine();
        // Search through ArrayList
        if (videos.contains(new Video(line3, null, null, null))) {
            System.out.println("Video found!");
        } 

仅当名称匹配时才会返回 contains = true。

【讨论】:

    猜你喜欢
    • 2023-03-22
    • 2020-11-19
    • 2012-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多