【问题标题】:ArrayList. Access to name by article by product type数组列表。按产品类型按文章访问名称
【发布时间】:2013-01-02 09:15:32
【问题描述】:

我的 Arraylist 包含 9 个人。每个人都有一个 String 类型的 name 值、一个 int 类型的 age 值和一个 Enum 类型的值(TV、SMARTPHONE、CAR)。我必须创建实现一个根据产品名称查找名称的方法。 如果 arrayListName 包含 SMARTPHONE,则返回所有带有智能手机的名称。

public void showByProduct(Product SMARTPHONE) {



    public void showByProductName(Product SMARTPHONE) {

            if (arrayListName.contains(SMARTPHONE))

                System.out.println("found"+nameofowner);
            else {
                System.out.println("not found");
            }
        }

【问题讨论】:

  • 能否请您粘贴您的努力.. :)

标签: java list sorting enums arraylist


【解决方案1】:

您需要遍历您的List,并为每个人检查它的product 字段是否具有您在方法中传递的值。

此外,您需要在方法中再添加一个 List,在其中添加与 Product Name 匹配的 Person,然后在最后返回 List

public List<Person> showByProductName(Product product) {

    List<Person> localList = new ArrayList<Person>();

    for (Person person: persons) {   // persons is the original List.
        if (person.getProduct() == product) {
            localList.add(person);
        }
    }

    return localList;
}

还有调用这个方法的地方,将返回值存储在List引用中:-

List<Person> result = showByProductName(Product.SMARTPHONE);
System.out.println(result);

请注意,您可以使用== 比较两个enum 值。因为enumsingleton

P.S:-不要将您的参数名称设为SMARTPHONE。这是一个枚举值。此外,根据Java 命名约定,变量名称应以小写字母开头,并在其后跟camelCasing

【讨论】:

    【解决方案2】:
    for (Person p : arrayListName){
        if(p.geProduct()==product)
            System.out.println("Found : " + p.name());
    }
    

    然而,这并不是很酷。我认为您应该使用枚举对您的人员进行排序。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-11-03
      • 2019-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 1970-01-01
      相关资源
      最近更新 更多