Java ArrayList - Find Item - Do I need Hash? -


im learning java , having problem arraylist. have read java doc , thinking maybe need hash thing?

i have object called catalogue has array list of objects created class called item. each item has fields size, colour, price, product code, (these item attributes). need include method in catalogue accepts product code , searches through arraylist find object matching product code. , returns product. have tostring method in item class lists of fields & values when called. maybe should returned when matching product code found in array list?

import java.util.arraylist;   public class catalogue {     private arraylist<item> catalogue;       public catalogue ()     {         catalogue = new arraylist<item>();      }      public void finditem(int code)     {         if(item.code == prodcode){          }         else{             system.out.println(catalogue.get(item));          }     } 

i looked @ java doc , read hash , maybe better me use rather iterator? i'm not sure route take. code half finished appreciated. thankls

what can depend on how close product codes are. i'm guessing aren't sequential, in case you'd indeed need use hashmap.

when store items in hashmap, store them keyed information you'd use when them up:

map<integer, item> catalog = new hashmap<integer, item>(); catalog.put(item.code, item);

then when need fetch item based on product code, use:

item item = map.get(code);


Comments

Popular posts from this blog

linux - Mailx and Gmail nss config dir -

c# - Is it possible to remove an existing registration from Autofac container builder? -

php - Mysql PK and FK char(36) vs int(10) -