Java: Practice Supermarket stores
Related to: large commodity, specific goods (in the case of books), store category
Goods,book,Supermart,
Product Class Goods:
Public interface Goods {//Commodity class public String getName ();p ublic int getcount ();p ublic float GetPrice ();}
Book:
Note: The replication hashcode, and equals is to implement the Delete button
Package Abc;public class Book implements Goods {private string name;private int count;private float price;public String ge Tname () {return name;} Public book () {super ();} Public book (String name, int. count, float price) {super (); this.name = Name;this.count = Count;this.price = Price;} public void SetName (String name) {this.name = name;} public int GetCount () {return count;} public void SetCount (int count) {This.count = count;} public float GetPrice () {return price;} public void Setprice (float price) {this.price = Price;} The replication hashcode, and equals is to implement the delete button @overridepublic int hashcode () {return This.name.hashCode () + new Integer (This.count). Hashcode () + new Float (This.price). Hashcode ();} The replication hashcode, and equals is to implement the Delete button @overridepublic Boolean equals (Object obj) {if (obj = = this) {return true;} if (! ( Obj instanceof book) {return false;} Book B = (book) obj;if (B.name.equals (this.name) && B.count = = This.count && B.price = this.price) {return true;} else {return false;}} @Overridepublic String toStRing () {return "title:" + name + ", Quantity:" + Count + ", Price:" + Prices;}}
Supermarket:
Note that the remove Delete method must be defined in the book to delete the associated Equals,hashcode method
Delete, need to replicate the book Inside Equals and Hascoderemove (Goods good)
Package Abc;import Java.util.arraylist;import Java.util.iterator;import Java.util.list;public class SuperMark { Private list<goods> allgoods;public Supermark () {this.allgoods = new arraylist<goods> ();} public void Add (Goods good) {This.allGoods.add (good);} Delete, need to copy the inside of the book Equals and hascodepublic void Remove (Goods good) {this.allGoods.remove (good);} Public list<goods> search (String keyword) {list<goods> temp = new arraylist<goods> ();iterator< Goods> iter = This.allGoods.iterator (), while (Iter.hasnext ()) {Goods g = iter.next (), if (G.getname (). INDEXOF (keyword )! =-1) {Temp.add (g);}} return temp;} Public list<goods> Getallgoods () {return this.allgoods;}}
Test:
public class Demo {public static void main (string[] args) {//TODO auto-generated method stub System.out.println ("Gaga"); Supermark sm = new Supermark () Sm.add (new book ("Java", 5,10.4f)), Sm.add ("net", 6,22.f), Sm.add ("PHP", 6,10f));p rint (Sm.search ("J"));} public static void print (List all) {Iterator iter = All.iterator (), while (Iter.hasnext ()) {System.out.println (Iter.next ( ));}}}
Java: Practice Supermarket stores