Java ArrayList – Find Item – Do I need Hash

arraylisthashmapjava

Im learning Java and having a problem with ArrayList. I have read the Java doc and am thinking I maybe need to do the hash thing?

I have an object called catalogue which has an array list of objects created from another class called item. Each item has fields for size, colour, price, product code, (these are item attributes). I need to include a method in catalogue which accepts a product code and searches through the ArrayList to find the object with matching product code. And then returns that product.
I have a toString method in my item class which lists all of the fields & their values when called. Maybe that is what should be returned when the matching product code is 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 at Java doc and I read about hash and maybe its better for me to use that rather than iterator? I'm not sure which route to take. My code is half finished
Any help greatly appreciated.
Thankls

Best Answer

What you do can depend on how close together your product codes are. I'm guessing they aren't sequential, in which case you'd indeed need to use a HashMap.

When you store items in the HashMap, store them keyed by the information you'd like to use when you look them up:

Map<Integer, Item> catalog = new HashMap<Integer, Item>();
catalog.put(item.code, item);

Then when you need to fetch an item based on its product code, use:

Item item = map.get(code);