了解ArrayLists和对象

时间:2017-12-01 09:21:07

标签: java object arraylist

我们假设我有以下Class Product

public class Product {
    // Variables.
    private String name;      // Name  
    private Double price;     // Price

    Product() {}    // Default constructor with no parameters.

    Product(String name, Double price) {    // Constructor with parameters.
        this.name = name;
        this.price = price;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Double getPrice() {
        return price;
    }
    public void setPrice(Double price) {
        this.price= price;
    }
    public String toString() {    // Overriding "toString()".
        return "\nName: " + this.name + "\nPrice: " + this.price;
    }


public boolean equals(Object obj) {    // Overriding equals()
   if(this == obj) {
      return true;
   }
   if(obj == null || obj.getClass() != this.getClass()) {
      return false;
   }
   Product product = (Product) obj;
   return this.name.equals(product.name)&& this.price.equals(product.price);
}
    }

现在,假设我的ArrayList中有一个Main.class而我的Main看起来像这样:

import java.util.*;
    import java.io.*;
    public class Main {
        private static BufferedReader r = new BufferedReader (new InputStreamReader(System.in));
        private static String readln() throws IOException{
            return r.readLine();
        }
        private static long readInput() throws IOException{    // Use this to read input for the menu options.
            return Integer.valueOf(readln());
        }
        public static void menu(){    // Menu
            System.out.println("-------------------------" +
                    "\nAdd new product(1)" +
                    "\nSearch for product(2)" +
                    "\nDelete product(3)" +
                    "\nShow all products(4)" +
                    "\nReturn the number of products(5)" +
                    "\nExit(-1)" +
                    "\n-------------------------");
        }

        public static void main (String args[]) throws IOException{
            // This is the ArrayList for the "Product".
            ArrayList<Product> products = new ArrayList<Product>();
            int option = 0;
            do {
                menu();
                option = (int)readInput();
                switch (option){
                    case 1:{
                        System.out.println("Insert product name: ");
                        String name= readln();
                        System.out.println("Insert product price: ");
                        Double price = Double.parseDouble(readln());
                        products.add(new Product(name, price));
                        break;
                    }
                    case 2:{
                        System.out.println("Insert product name: ");
                        String name= readln();
                        System.out.println("Insert product price: ");
                        Double price= Double.parseDouble(readln());
                        if ((products.contains(new Product (name, price)))){
                            System.out.println("Works!");
                        }

                        break;
                    }
                    case 3:{

                        break;
                    }
                    case 4:{

                        break;
                    }
                    case 5:{
                        System.out.println("Number of products: " + products.size());
    //This prints with no problems, therefor the objects DO exist in the ArrayList.
                        break;
                    }
                }
            }while((option > 0) && (option < 6));
        }
    }

根据this为了将对象插入ArrayList,您需要将其写为“ArrayListName.add(new ObjectName(param1, param2));”,或者您可以创建一个名为object1的对象,然后用ArrayListName.add(object1);添加它在我的情况下,根据我的理解,我将对象插入ArrayList但这些对象并不存在,因为如果我尝试使用被覆盖的{{1}方法,它不会打印任何东西。 如果我的理解是错误的,为什么不打印任何内容?根据this,我的方法是正确的。

如果我已正确理解this,则对象不需要变量来指向它们,但如果您将它们直接插入toString(),就像我一样,如何你应该得到一个对象的索引位置吗?因为在我的情况下ArrayList比较对象,所以你不能用它来搜索equals()。您也不能尝试“ArrayList”之类的内容,因为products.contains(name, price);使用.contains()

我也在考虑做this这样的事情,但是在我的情况下,如果你想创建一个新的equals()而不是Class这样的对象,它才有用。我也放弃了它,因为product1一直说它找不到forName()由于某种原因我无法找到原因。

“删除”选项怎么样?它的工作方式与“搜索”工作方式相同吗?

编辑:对于Class最后一行,您还可以输入:

equals()

2 个答案:

答案 0 :(得分:1)

为了使它工作,你还应该重写你的equals方法来主持人物对象中的字段overriding equals method

参数化构造函数中可能存在错误。它应该看起来像:

Product(final String name, final Double price) {    // Constructor with parameters.
    this.name = name;
    this.price = price;
}

最后一句话阻止我们改变传入参数的值。

根据上面的文章,实施应该是

@Override
public boolean equals(Object obj) {    // Overriding "equals()".
    // at first check if objects are the same -> your code
    if (this == obj) {
        return true;
    }

    // secondly we chack if objects are instances of the same class if not return false
    if (obj != null && this.getClass() != obj.getClass()) {
        return false;
    }

    // then compare objects fields. If fields have the same values we can say that objects are equal.
    Product product = (Product) obj;
    return this.name.equals(product.name) && this.price.equals(product.price);
}

要处理字段中的空值,我们可以编写其他检查。

使用equals方法的新实现来搜索列表中的元素,您可以将新的product实例传递给contains mathod

而不是

products.contains(name, price);

products.contains(new Product(name, price))

要从列表中删除元素,您可以先找到元素索引和使用remove方法。

products.remove(products.indexOf(new Product(name, price)))

答案 1 :(得分:1)

实际上,这不是理解使用ArrayList的好例子。首先,这个系列不适合产品清单。是的,您可以使用它,但Map要好得多。我不认为你正在学习Java。如果是这样,我更愿意使用Map代替List

此外,我建议避免使用选项编号。使用命名常量作为最小值,但使用OOP要好得多。例如。您可以使用enum,其中每个元素都是一个菜单选项。

E.g。如下。

public class Main {
    public static void main(String... args) {
        List<Product> products = readProducts();
        // final list of products
    }

    private static List<Product> readProducts() {
        Map<String, Product> products = new LinkedHashMap<>();

        try (Scanner scan = new Scanner(System.in)) {
            while (true) {
                MenuItem.show();
                MenuItem menuItem = MenuItem.parseOption(scan.nextInt());

                if (menuItem == MenuItem.EXIT)
                    break;

                menuItem.action(products, scan);
            }
        }

        return products.isEmpty() ? Collections.emptyList() : new ArrayList<>(products.values());
    }

    private enum MenuItem {
        ADD_NEW_PRODUCT(1, "Add new product") {
            @Override
            public void action(Map<String, Product> products, Scanner scan) {
                System.out.println("Insert product name: ");
                String name = scan.next();

                System.out.println("Insert product price: ");
                double price = scan.nextDouble();

                if (products.containsKey(name))
                    products.get(name).setPrice(price);
                else
                    products.put(name, new Product(name, price));
            }
        },
        SEARCH_FOR_PRODUCT(2, "Search for product"),
        DELETE_PRODUCT(3, "Delete product") {
            @Override
            public void action(Map<String, Product> products, Scanner scan) {
                System.out.println("Insert product name: ");
                String name = scan.next();

                products.remove(name);
            }
        },
        SHOW_ALL_PRODUCTS(4, "Show all products"),
        RETURN_THE_NUMBER_OF_PRODUCTS(5, "Return the number of products") {
            @Override
            public void action(Map<String, Product> products, Scanner scan) {
                System.out.println("Number of products: " + products.size());
            }
        },
        EXIT(-1, "Exit");

        private final int option;
        private final String title;

        MenuItem(int option, String title) {
            this.option = option;
            this.title = title;
        }

        public void action(Map<String, Product> products, Scanner scan) {
        }

        public static MenuItem parseOption(int option) {
            for (MenuItem menuItem : values())
                if (menuItem.option == option)
                    return menuItem;
            return EXIT;
        }

        public static void show() {
            System.out.println("-------------------------");

            for (MenuItem menuItem : values())
                System.out.printf("%s(%d)\n", menuItem.title, menuItem.option);

            System.out.println("-------------------------");
        }
    }
}