Link to home
Start Free TrialLog in
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

asked on

ArrayList vs HashMap

Hi,

Is there a container class that is somewhat of a hybrid between ArrayList and HashMap? I want to do soemthing like:

class Great {
    int m_n;
    public Great(int n) { m_n = n; }
    public void whatever() {};
}

public void test()
{
    ArrayList<Great> t = new ArrayList<Great>();
    t.add(new Great(5));
    t.add(new Great(2));
    t.add(new Great(0));

    if (t.contains(5)) {
        t.getKey(5).whatever();
    }

    for (int i =  0; i < t.size(); i++) {
        t.get(i).whatever();
    }
}

I want to be able to look an element up by some key defined inside the 'Great' class, but I also want to be able to access each element in the order they were inserted into the container. Right now I'm searching the array start to end everytime I need to find a particular instance of Great.

HashMap almost does what I want, but you need the key in the first place which makes it look clumsy:

    HashMap<Integer, Great> t = new HashMap(...);
    t.put(5, new Great(5));
    t.put(2, new Great(2));
    t.put(0, new Great(0));


Thanks
ASKER CERTIFIED SOLUTION
Avatar of CEHJ
CEHJ
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of DJ_AM_Juicebox
DJ_AM_Juicebox

ASKER

Yeah I checked LinkedHashMap and had thought I found what I was looking for - but you're right, it doesn't quite do it,

Thanks
:-)