是否可以根据字段获取对象的实例? [英] Is it possible to get an instance of an object based on a field?

查看:75
本文介绍了是否可以根据字段获取对象的实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些包含一些产品的数组列表:



I have an array list with some products:

ArrayList<Products> catalog = new ArrayList<Products>();
ArrayList<Products> cartArray = new ArrayList<>();

        catalog.add(new SSD("   SSD", "red", 322, "Storage"));
        catalog.add(new Laptop("Laptop", "white", 900, "Laptops"));
        catalog.add(new Laptop("Laptop", "white", 900, "Laptops"));



我想在购物车中添加一个上面的物体。用户应该输入产品的名称,我有一个名为findProduct的方法,它检查用户输入的产品名称是否存在于带有产品的数组中。

如果名称存在,方法应该获取对象的实例并将其添加到名为cartArray的另一个ArrayList中。我将把方法发布到方法findProduct。



我尝试过的方法:




I want to add in my cart one of the objects from above. The user should enter the name of the product and I have a method called "findProduct" which checks if the name of product entered by user exists in my array with products.
If the name exists the method should get the instance of the object and to add it into another ArrayList called "cartArray". I am going to post bellow to the method findProduct.

What I have tried:

public void findProduct(String name, int quantity) {

      for (int i = 0; i < catalog.size(); i++) {
          if (name.equals(catalog.get(i).getName())) {
              System.out.printf("Product: %s    Quantity: %d  | Has been added in your cart.", name, quantity);
              cartArray.add =" HERE!!! I don't really know how to get the instance of the product that has the name of variable 'String name'";
              break;
          } else {
              System.out.printf("We don't have the product '%s' in our store.", name);
              break;
          }
      }

  }



提前谢谢!


Thank you in advance!

推荐答案

在你的循环中,catalog.get(i)是你要找的实例。



你可以这样做:

In your loop, catalog.get(i) is the instance you are looking for.

You could do something like this:
public void findProduct(String name, int quantity) {
      for (int i = 0; i < catalog.size(); i++) {
          if (name.equals(catalog.get(i).getName())) {
              System.out.printf("Product: %s    Quantity: %d  | Has been added in your cart.", name, quantity);
              cartArray.add(catalog.get(i));
              return;
          }
      }
      System.out.printf("We don't have the product '%s' in our store.", name);
  }


这篇关于是否可以根据字段获取对象的实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆