java - How to compare Objects attributes in an ArrayList? -
i new java , have exhausted of current resources find answer. wondering if possible access objects first property see if matches particular integer?
for example, trying obtain product within database searching it's product id. therefore, if create 2 products such as, product ipad = new product(12345, "ipad", 125.0, deptcode.computer);
, product ipod = new product(12356, "ipod", 125.0, deptcode.electronics);
(i have included product class below), , add them arraylist such as, list<product> products = new arraylist<product>();
how can loop through arraylist in order find product id? method working on:
list<product> products = new arraylist<product>(); @override public product getproduct(int productid) { // todo auto-generated method stub for(int i=0; i<products.size(); i++){ //if statement go here //i trying: if (product.getid() == productid) { system.out.println(products.get(i)); } return null; }`
i know can include conditional statement in loop cant figure out how access getid() method in product class compare productid parameter?
package productdb; public class product { private integer id; private string name; private double price; private deptcode dept; public product(string name, double price, deptcode code) { this(null, name, price, code); } public product(integer id, string name, double price, deptcode code) { this.id = id; this.name = name; this.price = price; this.dept = code; } public string getname() { return name; } public double getprice() { return price; } public integer getid() { return id; } public void setid(integer id) { this.id = id; } public deptcode getdept() { return dept; } public void setdept(deptcode dept) { this.dept = dept; } public void setname(string name) { this.name = name; } public void setprice(double price) { this.price = price; } @override public string tostring() { string info = string.format("product [productid:%d, name: %s, dept: %s, price: %.2f", id, name, dept, price); return info; } }
please let me know
you have got product
out of list<product>
in following statement:
system.out.println(products.get(i));
now, have got product
, it's id, can call it's getid()
method:
if (product.get(i).getid() == productid) { // return product. }
i suggest use enhanced for-loop instead of traditional loop this:
for (product product: products) { // have product. id if (product.getid() == productid) { return product; } }
also, should change type of productid integer
int
. don't need wrapper type there.
Comments
Post a Comment