数组对象
package day_21; import java.util.Objects; public class Product { private String name; private double price; public String getName() { return name; } public double getPrice() { return price; } public Product() { } public Product(String name, double price) { this.name = name; this.price = price; } @Override public String toString() { return "Product{" + "name='" + name + '\'' + ", price=" + price + '}'; } @Override //重写equal hashCode两个方法 public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Product product = (Product) o; return Double.compare(product.price, price) == 0 && Objects.equals(name, product.name); } @Override public int hashCode() { return Objects.hash(name, price); } } package day_21; import java.util.Arrays; public class ShopCar { private int size=0; Product []products; //定义一个数组保存产品 public ShopCar() { products=new Product[5]; //将数组大小定义为5 } public void add(Product product){ if(size>=products.length){ //如果产品量多于数组大小,将数组扩容 products= Arrays.copyOf(products, products.length*3/2); } products[size]=product; size++; } public void delete(Product product){ for(int j=0;j<size;j++){ if(products[j].equals(product)){ //寻找需要删除的产品 products[j]=products[size-1]; //将最后一个产品赋值给需要删除产品对应的下标 size--; } } } public void sum(){ double sumPrice=0.0; for(int i=0;i<size;i++){ System.out.println("name="+products[i].getName()+"\t"+products[i].getPrice()); sumPrice+=products[i].getPrice(); } System.out.println("sumPrice="+sumPrice); } } package day_21; /** * 数组对象 */ public class Test { public static void main(String[] args) { ShopCar shopCar=new ShopCar(); shopCar.add(new Product("联想",5000)); shopCar.add(new Product("戴尔",6000)); shopCar.add(new Product("华为",9000)); shopCar.add(new Product("小米",8000)); shopCar.delete(new Product("戴尔",6000)); shopCar.sum(); } }